fork from github

This commit is contained in:
Jeff Cliff 2021-09-30 23:12:19 -06:00
commit 8c92b374a9
640 changed files with 36778 additions and 0 deletions

4
Gemfile Normal file
View File

@ -0,0 +1,4 @@
source "https://rubygems.org"
gem "fastlane"

213
Gemfile.lock Normal file
View File

@ -0,0 +1,213 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.3)
addressable (2.8.0)
public_suffix (>= 2.0.2, < 5.0)
artifactory (3.0.15)
atomos (0.1.3)
aws-eventstream (1.2.0)
aws-partitions (1.494.0)
aws-sdk-core (3.120.0)
aws-eventstream (~> 1, >= 1.0.2)
aws-partitions (~> 1, >= 1.239.0)
aws-sigv4 (~> 1.1)
jmespath (~> 1.0)
aws-sdk-kms (1.48.0)
aws-sdk-core (~> 3, >= 3.120.0)
aws-sigv4 (~> 1.1)
aws-sdk-s3 (1.101.0)
aws-sdk-core (~> 3, >= 3.120.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.1)
aws-sigv4 (1.3.0)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
claide (1.0.3)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
declarative (0.0.20)
digest-crc (0.6.4)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
dotenv (2.7.6)
emoji_regex (3.2.2)
excon (0.85.0)
faraday (1.7.1)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0.1)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.1)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
multipart-post (>= 1.2, < 3)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.7)
faraday (>= 0.8.0)
http-cookie (~> 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.0)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-net_http (1.0.1)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday_middleware (1.1.0)
faraday (~> 1.0)
fastimage (2.2.5)
fastlane (2.193.0)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored
commander (~> 4.6)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (~> 2.0.0)
naturally (~> 2.2)
optparse (~> 0.1.1)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.3)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (>= 1.4.5, < 2.0.0)
tty-screen (>= 0.6.3, < 1.0.0)
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.3.0)
xcpretty-travis-formatter (>= 0.0.3)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.10.0)
google-apis-core (>= 0.4, < 2.a)
google-apis-core (0.4.1)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
mini_mime (~> 1.0)
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
webrick
google-apis-iamcredentials_v1 (0.7.0)
google-apis-core (>= 0.4, < 2.a)
google-apis-playcustomapp_v1 (0.5.0)
google-apis-core (>= 0.4, < 2.a)
google-apis-storage_v1 (0.6.0)
google-apis-core (>= 0.4, < 2.a)
google-cloud-core (1.6.0)
google-cloud-env (~> 1.0)
google-cloud-errors (~> 1.0)
google-cloud-env (1.5.0)
faraday (>= 0.17.3, < 2.0)
google-cloud-errors (1.1.0)
google-cloud-storage (1.34.1)
addressable (~> 2.5)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.1)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
mini_mime (~> 1.0)
googleauth (0.17.1)
faraday (>= 0.17.3, < 2.0)
jwt (>= 1.4, < 3.0)
memoist (~> 0.16)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (~> 0.15)
highline (2.0.3)
http-cookie (1.0.4)
domain_name (~> 0.5)
httpclient (2.8.3)
jmespath (1.4.0)
json (2.5.1)
jwt (2.2.3)
memoist (0.16.2)
mini_magick (4.11.0)
mini_mime (1.1.1)
multi_json (1.15.0)
multipart-post (2.0.0)
nanaimo (0.3.0)
naturally (2.2.1)
optparse (0.1.1)
os (1.1.1)
plist (3.6.0)
public_suffix (4.0.6)
rake (13.0.6)
representable (3.1.1)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.2.5)
rouge (2.0.7)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
security (0.1.3)
signet (0.15.0)
addressable (~> 2.3)
faraday (>= 0.17.3, < 2.0)
jwt (>= 1.5, < 3.0)
multi_json (~> 1.10)
simctl (1.6.8)
CFPropertyList
naturally
terminal-notifier (2.0.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
trailblazer-option (0.1.1)
tty-cursor (0.7.1)
tty-screen (0.8.1)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.7)
unicode-display_width (1.7.0)
webrick (1.7.0)
word_wrap (1.0.0)
xcodeproj (1.21.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
PLATFORMS
ruby
DEPENDENCIES
fastlane
BUNDLED WITH
2.1.4

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>.

44
README.md Normal file
View File

@ -0,0 +1,44 @@
# ![Feature graphic](fastlane/metadata/android/en-US/images/featureGraphic.png)
[![Latest release](https://img.shields.io/github/tag-date/ashutoshgngwr/noice.svg?color=orange&label=release)](https://GitHub.com/ashutoshgngwr/noice/tags/)
[![GitHub license](https://img.shields.io/github/license/ashutoshgngwr/noice.svg)](https://github.com/ashutoshgngwr/noice/blob/master/LICENSE)
[![Translation status](https://hosted.weblate.org/widgets/noice/-/svg-badge.svg)](https://hosted.weblate.org/engage/noice/)
[![Financial contributors](https://opencollective.com/noice/tiers/badge.svg)](https://opencollective.com/noice)
[![Android](https://github.com/ashutoshgngwr/noice/workflows/Android/badge.svg)](https://github.com/ashutoshgngwr/noice/actions?query=workflow%3AAndroid)
[![Cast Receiver](https://github.com/ashutoshgngwr/noice/workflows/Cast%20Receiver/badge.svg)](https://github.com/ashutoshgngwr/noice/actions?query=workflow%3A%22Cast+Receiver%22)
[![codecov](https://codecov.io/gh/ashutoshgngwr/noice/branch/master/graph/badge.svg)](https://codecov.io/gh/ashutoshgngwr/noice)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/67635a43989c4dbcb6c3472375dc1e5f)](https://www.codacy.com/manual/ashutoshgngwr/noice)
For a lot of people, a little background noise is helpful to calm down and focus. In some cases, it's also a boost to productivity. Background noise can also help minimize the effects of stress.
Noice is an app that allows you to create your own set of background sounds by mixing clips from environmental sources. Create your perfect surroundings by combining different sounds to drown out distractions so you can focus on your work, or generate serene, peaceful environments that encourage you to fall asleep.
## Download
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="100">][f-droid-link]
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en-play-badge.png" alt="Get it on Google Play" height="100">][google-play-link]
## Screenshots
| | | |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| ![Screenshot 1](fastlane/metadata/android/en-US/images/phoneScreenshots/1.png) | ![Screenshot 2](fastlane/metadata/android/en-US/images/phoneScreenshots/2.png) | ![Screenshot 3](fastlane/metadata/android/en-US/images/phoneScreenshots/3.png) |
| ![Screenshot 4](fastlane/metadata/android/en-US/images/phoneScreenshots/4.png) | ![Screenshot 5](fastlane/metadata/android/en-US/images/phoneScreenshots/5.png) | ![Screenshot 6](fastlane/metadata/android/en-US/images/phoneScreenshots/6.png) |
## Documentation
1. [All notable changes](https://ashutoshgngwr.github.io/noice/CHANGELOG) to the
project over time
2. The [list of
contributors](https://ashutoshgngwr.github.io/noice/contributors)
3. [How can you contribute?](https://ashutoshgngwr.github.io/noice/contributing)
4. [Code of Conduct](https://ashutoshgngwr.github.io/noice/code-of-conduct)
5. [Privacy Policy](https://ashutoshgngwr.github.io/noice/privacy-policy) for
application users
## License
[GNU GPL v3](LICENSE)
[google-play-link]: https://play.google.com/store/apps/details?id=com.github.ashutoshgngwr.noice&referrer=utm_source%3DGitHub%26utm_campaign%3DREADME
[f-droid-link]: https://f-droid.org/app/com.github.ashutoshgngwr.noice

148
app/build.gradle Normal file
View File

@ -0,0 +1,148 @@
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.adarshr.test-logger' version '3.0.0'
}
apply from: 'jacoco.gradle'
android {
compileSdkVersion 30
defaultConfig {
applicationId 'com.github.ashutoshgngwr.noice'
minSdkVersion 21
targetSdkVersion 30
versionCode 52
versionName '1.3.3'
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildFeatures {
viewBinding true
}
buildTypes {
debug {
applicationIdSuffix '.debug'
testCoverageEnabled true
}
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
flavorDimensions 'tier'
productFlavors {
free {
dimension 'tier'
buildConfigField 'boolean', 'IS_FREE_BUILD', 'true'
}
full {
dimension 'tier'
buildConfigField 'boolean', 'IS_FREE_BUILD', 'false'
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
useIR = true
jvmTarget = 1.8
freeCompilerArgs += ["-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"]
}
testOptions {
unitTests {
includeAndroidResources = true
all {
testlogger {
theme 'mocha'
}
}
}
}
}
dependencies {
def fragmentVersion = '1.3.6'
def testCoreVersion = '1.3.0'
def junitVersion = '4.13.2'
def mockkVersion = '1.12.0'
def espressoVersion = '3.3.0'
def coroutinesVersion = '1.5.2'
// TODO: move this to stable release. The latest stable release (2.3.5) causes a crash with error
// `java.lang.RuntimeException: Unknown animation name: x`
// Although, the crash only occurs on the Play Store variant..?
def navVersion = '2.4.0-alpha06'
implementation 'androidx.activity:activity-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.browser:browser:1.3.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.drawerlayout:drawerlayout:1.1.1'
implementation "androidx.fragment:fragment-ktx:$fragmentVersion"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.media:media:1.4.1'
implementation 'androidx.mediarouter:mediarouter:1.2.5'
implementation "androidx.navigation:navigation-fragment-ktx:$navVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navVersion"
implementation 'androidx.preference:preference-ktx:1.1.1'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'com.github.AppIntro:AppIntro:6.1.0'
implementation 'io.github.medyo:android-about-page:2.0.0'
implementation 'com.google.android.exoplayer:exoplayer-core:2.11.8'
implementation 'com.google.android:flexbox:2.0.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'com.google.code.gson:gson:2.8.8'
implementation 'com.hopenlib.library:flextools:1.0.1'
implementation 'com.ncorti:slidetoact:0.9.0'
implementation 'io.noties.markwon:core:4.6.2'
implementation 'org.greenrobot:eventbus:3.1.1'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
fullImplementation 'com.android.billingclient:billing-ktx:4.0.0'
fullImplementation 'com.google.android.gms:play-services-base:17.6.0'
fullImplementation 'com.google.android.gms:play-services-cast-framework:20.0.0'
fullImplementation 'com.google.android.play:core:1.10.1'
fullImplementation platform('com.google.firebase:firebase-bom:28.4.0')
fullImplementation 'com.google.firebase:firebase-analytics-ktx'
fullImplementation 'com.google.firebase:firebase-crashlytics-ktx'
fullImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
testImplementation "androidx.test:core:$testCoreVersion"
testImplementation "io.mockk:mockk:$mockkVersion"
testImplementation "junit:junit:$junitVersion"
testImplementation 'org.robolectric:robolectric:4.5.1'
testImplementation 'org.skyscreamer:jsonassert:1.5.0'
testFullImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
androidTestImplementation "androidx.test:core:$testCoreVersion"
androidTestImplementation "androidx.test:rules:1.4.0"
androidTestImplementation "androidx.test:runner:1.4.0"
androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoVersion"
androidTestImplementation "androidx.test.espresso:espresso-intents:$espressoVersion"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation "io.mockk:mockk-android:$mockkVersion"
androidTestImplementation "junit:junit:$junitVersion"
androidTestFullImplementation 'tools.fastlane:screengrab:2.1.0'
debugImplementation "androidx.fragment:fragment-testing:$fragmentVersion"
}

68
app/google-services.json Normal file
View File

@ -0,0 +1,68 @@
{
"project_info": {
"project_number": "988644359741",
"project_id": "noice-android",
"storage_bucket": "noice-android.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:988644359741:android:5f9097fe9d7b6944a63454",
"android_client_info": {
"package_name": "com.github.ashutoshgngwr.noice"
}
},
"oauth_client": [
{
"client_id": "988644359741-6avtf2r8i748vfrhnndbedbc0l7b0677.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyD0bJzJla8JZSyAXe3AqzxQ7z0i0gCTurI"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "988644359741-6avtf2r8i748vfrhnndbedbc0l7b0677.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:988644359741:android:1307df0db8c918c9a63454",
"android_client_info": {
"package_name": "com.github.ashutoshgngwr.noice.debug"
}
},
"oauth_client": [
{
"client_id": "988644359741-6avtf2r8i748vfrhnndbedbc0l7b0677.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyD0bJzJla8JZSyAXe3AqzxQ7z0i0gCTurI"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "988644359741-6avtf2r8i748vfrhnndbedbc0l7b0677.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}

62
app/jacoco.gradle Normal file
View File

@ -0,0 +1,62 @@
// https://github.com/dampcake/Robolectric-JaCoCo-Sample/blob/master/jacoco.gradle
apply plugin: 'jacoco'
jacoco {
// https://bintray.com/bintray/jcenter/org.jacoco:org.jacoco.core
toolVersion = '0.8.7'
}
android {
testOptions {
unitTests.all {
jacoco {
includeNoLocationClasses = true
excludes = ['jdk.internal.*']
}
}
}
}
project.afterEvaluate {
android.applicationVariants.all { variant ->
def taskName = "test${variant.name.capitalize()}Coverage"
def testTask = "test${variant.name.capitalize()}UnitTest"
tasks.create(name: "${taskName}", type: JacocoReport, dependsOn: "${testTask}") {
group = 'Reporting'
description = "Generate Jacoco coverage reports for the ${variant.name} build variant."
def sourceDirs = ['src/main/java'] + android.sourceSets[variant.name].java.srcDirs
def execDataFile = "${project.buildDir}/jacoco/${testTask}.exec"
def classFiles = fileTree(
dir: "${project.buildDir}/tmp/kotlin-classes/${variant.name}",
excludes: ['**/R.class',
'**/R$*.class',
'**/*$ViewInjector*.*',
'**/*$ViewBinder*.*',
'**/BuildConfig.*',
'**/Manifest*.*']
)
sourceDirectories.setFrom(files(sourceDirs))
executionData.setFrom(files(execDataFile))
classDirectories.setFrom(classFiles)
reports {
xml.enabled = true
xml.destination file("${project.buildDir}/reports/jacoco/${taskName}/report.xml")
html.enabled = true
}
}
}
tasks.create(name: 'testCoverage', type: JacocoReport) {
group = 'Reporting'
description = 'Generate Jacoco coverage reports for the all build variants.'
android.applicationVariants.all { variant ->
dependsOn "test${variant.name.capitalize()}Coverage"
}
}
}

2
app/local.properties Normal file
View File

@ -0,0 +1,2 @@
sdk.dir=/opt/android-sdk
sdk-location=/opt/android-sdk

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

@ -0,0 +1,37 @@
# crashlytics
-keepattributes SourceFile,LineNumberTable
-keep public class * extends java.lang.Exception
# EventBus rules
-keepattributes *Annotation*
-keepclassmembers class * {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# GSON rules https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation, already present in EventBus rules
-keepattributes *Annotation*
# Gson specific classes
-dontwarn sun.misc.**
# Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapter
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
# Since we only serialise/deserialise @Expose fields in Noice, keep all will with members annotated as such.
-keepclassmembers class * {
@com.google.gson.annotations.Expose <fields>;
}
# Preserve names of all fragment classes for analytics
-keepnames class com.github.ashutoshgngwr.noice.fragment.*

View File

@ -0,0 +1,152 @@
package com.github.ashutoshgngwr.noice
import android.content.Intent
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.ViewInteraction
import androidx.test.espresso.action.MotionEvents
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.*
import com.github.ashutoshgngwr.noice.widget.DurationPicker
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.slider.Slider
import com.google.android.material.textfield.TextInputLayout
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.*
import org.hamcrest.TypeSafeMatcher
/**
* [EspressoX] contains the custom extended util implementations for Espresso.
*/
object EspressoX {
/**
* [clickInItem] performs a click action on item with the given [viewId] inside currently
* matched view.
*/
fun clickInItem(@IdRes viewId: Int): ViewAction {
return object : ViewAction {
override fun getDescription() = "Click on view with specified id"
override fun getConstraints() = hasDescendant(withId(viewId))
override fun perform(uiController: UiController, view: View) {
view.findViewById<View>(viewId).also { it.performClick() }
}
}
}
/**
* [slide] emulates slide action on the provided [Slider] widget.
*/
fun slide(value: Float): ViewAction {
return object : ViewAction {
override fun getDescription() = "Emulate user input on a slider"
override fun getConstraints() = instanceOf<View>(Slider::class.java)
override fun perform(uiController: UiController, view: View) {
view as Slider
val height = view.height - view.paddingTop - view.paddingBottom
val location = intArrayOf(0, 0)
view.getLocationOnScreen(location)
val xOffset = location[0].toFloat() + view.paddingStart + view.trackSidePadding
val range = view.valueTo - view.valueFrom
val xStart = (((view.value - view.valueFrom) / range) * view.trackWidth) + xOffset
val x = (((value - view.valueFrom) / range) * view.trackWidth) + xOffset
val y = location[1] + view.paddingTop + (height.toFloat() / 2)
val startCoordinates = floatArrayOf(xStart, y)
val endCoordinates = floatArrayOf(x, y)
val precision = floatArrayOf(1f, 1f)
// Send down event, and send up
val down = MotionEvents.sendDown(uiController, startCoordinates, precision).down
uiController.loopMainThreadForAtLeast(100)
MotionEvents.sendMovement(uiController, down, endCoordinates)
uiController.loopMainThreadForAtLeast(100)
MotionEvents.sendUp(uiController, down, endCoordinates)
}
}
}
/**
* Returns a [ViewAction] that invokes [DurationPicker.onDurationAddedListener] with the given
* [durationSecs].
*/
fun addDurationToPicker(durationSecs: Long): ViewAction {
return object : ViewAction {
override fun getDescription() = "add duration to a DurationPicker"
override fun getConstraints() = instanceOf<View>(DurationPicker::class.java)
override fun perform(uiController: UiController, view: View) {
view as DurationPicker
view.invokeOnDurationAddedListener(durationSecs * 1000L)
}
}
}
/**
* Returns a [Matcher] that matches reset button of the [DurationPicker] view.
*/
fun withDurationPickerResetButton(durationPickerMatcher: Matcher<View>): Matcher<View> {
return allOf(isDescendantOfA(durationPickerMatcher), withId(R.id.reset_button))
}
/**
* [withErrorText] matches [TextInputLayout]s using the provided error text.
*/
fun withErrorText(@StringRes expectedErrorText: Int): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description?) = Unit
override fun matchesSafely(item: View?): Boolean {
if (item !is TextInputLayout) return false
val error = item.error ?: return false
return item.context.getString(expectedErrorText) == error.toString()
}
}
}
/**
* Returns a matcher that matches the nested intent sent with an Intent chooser.
*/
fun hasIntentChooser(matcher: Matcher<Intent>): Matcher<Intent> {
return allOf(
hasAction(Intent.ACTION_CHOOSER),
hasExtra(`is`(Intent.EXTRA_INTENT), matcher)
)
}
/**
* [noop] returns a [ViewAction] that does nothing.
*/
fun noop(): ViewAction {
return object : ViewAction {
override fun getDescription() = "no-op"
override fun getConstraints() = any(View::class.java)
override fun perform(uiController: UiController, view: View) = Unit
}
}
fun withBottomNavSelectedItem(@IdRes id: Int): Matcher<View> = object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description?) = Unit
override fun matchesSafely(item: View?): Boolean {
return item is BottomNavigationView && item.selectedItemId == id
}
}
/**
* Matches [matchers] in a root that [isDialog].
*/
fun onViewInDialog(vararg matchers: Matcher<View>): ViewInteraction {
return onView(allOf(*matchers)).inRoot(isDialog())
}
}

View File

@ -0,0 +1,76 @@
package com.github.ashutoshgngwr.noice.activity
import android.content.Intent
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.FragmentScenario
import androidx.lifecycle.Lifecycle
import androidx.media.AudioAttributesCompat
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.swipeRight
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import io.mockk.every
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AlarmRingerActivityTest {
@Before
fun setup() {
mockkObject(PlaybackController)
every { PlaybackController.setAudioUsage(any(), any()) } returns Unit
every { PlaybackController.pause(any()) } returns Unit
every { PlaybackController.playPreset(any(), any()) } returns Unit
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testWithoutPresetID() {
val scenario = ActivityScenario.launch(AlarmRingerActivity::class.java)
verify(exactly = 1, timeout = 5000L) { PlaybackController.pause(any()) }
assertEquals(Lifecycle.State.DESTROYED, scenario.state)
}
@Test
fun testWithPresetID() {
val presetID = "test-preset-id"
// cannot launch Activity using `ActivityScenario.launch(Intent)` method. For whatever reasons,
// it increases the startup time for all subsequent `ActivityScenario.launch(Class)`s from
// other classes.
FragmentScenario.launch(Fragment::class.java).onFragment {
it.startActivity(
Intent(it.requireContext(), AlarmRingerActivity::class.java)
.putExtra(AlarmRingerActivity.EXTRA_PRESET_ID, presetID)
)
}
onView(withId(R.id.dismiss_slider)).check(matches(isDisplayed()))
verify(exactly = 1, timeout = 5000L) {
PlaybackController.setAudioUsage(any(), AudioAttributesCompat.USAGE_ALARM)
PlaybackController.playPreset(any(), presetID)
}
onView(withId(R.id.dismiss_slider)).perform(swipeRight())
verify(exactly = 1, timeout = 5000L) {
PlaybackController.setAudioUsage(any(), AudioAttributesCompat.USAGE_MEDIA)
PlaybackController.pause(any())
}
}
}

View File

@ -0,0 +1,117 @@
package com.github.ashutoshgngwr.noice.activity
import android.app.Activity
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.swipeLeft
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.R
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AppIntroActivityTest {
private lateinit var activityScenario: ActivityScenario<AppIntroActivity>
@Before
fun setup() {
activityScenario = ActivityScenario.launch(AppIntroActivity::class.java)
}
@After
fun teardown() {
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit { clear() }
}
@Test
fun testOnSkipPressed() {
onView(withId(R.id.skip))
.check(matches(isDisplayed()))
.perform(click())
// not using activityScenario.state since it never transitions to destroyed without adding an
// arbitrary wait before assertions.
assertEquals(Activity.RESULT_CANCELED, activityScenario.result?.resultCode)
// should update the preferences
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.getBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, false)
.also { assertTrue(it) }
}
@Test
fun testOnDonePressed() {
while (true) {
try {
onView(withId(R.id.done))
.check(matches(isDisplayed()))
.perform(click())
break
} catch (e: AssertionError) {
onView(withId(R.id.view_pager))
.check(matches(isDisplayed()))
.perform(swipeLeft())
}
}
// not using activityScenario.state since it never transitions to destroyed without adding an
// arbitrary wait before assertions.
assertEquals(Activity.RESULT_CANCELED, activityScenario.result?.resultCode)
// should update the preferences
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.getBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, false)
.also { assertTrue(it) }
}
@Test
fun testMaybeStart_whenUserIsTryingToSeeItForTheFirstTime() {
Intents.init()
try {
// leveraging currently created activityScenario to start another instance of self. (:
activityScenario.onActivity {
AppIntroActivity.maybeStart(it)
}
intended(hasComponent(AppIntroActivity::class.qualifiedName))
} finally {
Intents.release()
}
}
@Test
fun testMaybeStart_whenUserHasAlreadySeenIt() {
Intents.init()
try {
// when user has already seen the activity once, i.e., if the preference is present in the
// storage, maybeStart shouldn't start the activity.
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit { putBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, true) }
activityScenario.onActivity {
AppIntroActivity.maybeStart(it)
}
assertEquals(0, Intents.getIntents().size)
} finally {
Intents.release()
}
}
}

View File

@ -0,0 +1,180 @@
package com.github.ashutoshgngwr.noice.activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.navigation.findNavController
import androidx.preference.PreferenceManager
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ActivityScenario.launch
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.BuildConfig
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.provider.AnalyticsProvider
import com.github.ashutoshgngwr.noice.provider.BillingProvider
import com.github.ashutoshgngwr.noice.provider.CrashlyticsProvider
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
private lateinit var activityScenario: ActivityScenario<MainActivity>
@Before
fun setup() {
// mark app intro as seen to run main activity tests in peace
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit {
putBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, true)
putBoolean(MainActivity.PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, true)
putBoolean(MainActivity.PREF_HAS_SEEN_V2_ANNOUNCEMENT, true)
}
activityScenario = launch(MainActivity::class.java)
}
@After
fun teardown() {
unmockkAll()
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit { clear() }
}
@Test
fun testNavDestinationExtra() {
activityScenario = Intent(ApplicationProvider.getApplicationContext(), MainActivity::class.java)
.let {
it.putExtra(MainActivity.EXTRA_NAV_DESTINATION, R.id.about)
launch(it)
}
activityScenario.onActivity {
val navController = it.findNavController(R.id.nav_host_fragment)
assertEquals(R.id.about, navController.currentDestination?.id)
}
}
@Test
fun testAppTheme() {
val nightModes = arrayOf(
AppCompatDelegate.MODE_NIGHT_NO,
AppCompatDelegate.MODE_NIGHT_YES,
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
)
val mockRepo = mockk<SettingsRepository>(relaxed = true)
mockkObject(SettingsRepository)
every { SettingsRepository.newInstance(any()) } returns mockRepo
for (nightMode in nightModes) {
every { mockRepo.getAppThemeAsNightMode() } returns nightMode
activityScenario.recreate()
assertEquals(nightMode, AppCompatDelegate.getDefaultNightMode())
}
}
@Test
fun testPresetUriIntent() {
mockkObject(PlaybackController)
val inputs = arrayOf(
"https://ashutoshgngwr.github.io/noice/preset?name=test&playerStates=[]",
"noice://preset?name=test&playerStates=[]"
)
every { PlaybackController.playPresetFromUri(any(), any()) } returns Unit
for (input in inputs) {
val uri = Uri.parse(input)
activityScenario.onActivity {
it.startActivity(
Intent(it, MainActivity::class.java)
.setAction(Intent.ACTION_VIEW)
.setData(uri)
)
}
verify(exactly = 1, timeout = 5000L) { PlaybackController.playPresetFromUri(any(), uri) }
}
}
@Test
fun testUsageDataCollectionDialog() {
val mockAnalyticsProvider: AnalyticsProvider = mockk(relaxed = true)
val mockCrashlyticsProvider: CrashlyticsProvider = mockk(relaxed = true)
ApplicationProvider.getApplicationContext<NoiceApplication>().apply {
analyticsProvider = mockAnalyticsProvider
crashlyticsProvider = mockCrashlyticsProvider
}
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit { remove(MainActivity.PREF_HAS_SEEN_DATA_COLLECTION_CONSENT) }
activityScenario.recreate()
if (BuildConfig.IS_FREE_BUILD) {
onView(withText(R.string.share_usage_data_consent_title)).check(doesNotExist())
return
}
onView(withText(R.string.share_usage_data_consent_title))
.check(matches(isDisplayed()))
onView(withText(R.string.accept)).perform(click())
verify(exactly = 1) {
mockAnalyticsProvider.setCollectionEnabled(true)
mockCrashlyticsProvider.setCollectionEnabled(true)
}
}
@Test
fun testBillingProviderListener() {
if (BuildConfig.IS_FREE_BUILD) { // free flavor doesn't have billing provider scenarios
return
}
val mockBillingProvider: BillingProvider = mockk(relaxed = true)
ApplicationProvider.getApplicationContext<NoiceApplication>()
.billingProvider = mockBillingProvider
activityScenario.recreate()
val slot = slot<BillingProvider.PurchaseListener>()
verify { mockBillingProvider.init(any(), capture(slot)) }
assertTrue(slot.isCaptured)
activityScenario.onActivity {
slot.captured.onPending(listOf("test-sku"))
}
onView(withText(R.string.payment_pending))
.check(matches(isDisplayed()))
val testOrderID = "test-order-id"
activityScenario.onActivity {
slot.captured.onComplete(listOf(), testOrderID)
}
EspressoX.onViewInDialog(withId(R.id.positive)).perform(click()) // close the dialog
verify { mockBillingProvider.consumePurchase(testOrderID) }
}
}

View File

@ -0,0 +1,74 @@
package com.github.ashutoshgngwr.noice.activity
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.model.Preset
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ShortcutHandlerActivityTest {
@After
fun teardown() {
unmockkAll()
}
@Test
fun testOnCreate() {
mockkObject(PresetRepository.Companion, PlaybackController)
every { PlaybackController.playPreset(any(), any()) } returns Unit
val mockRepo = mockk<PresetRepository>()
every { PresetRepository.newInstance(any()) } returns mockRepo
val presetIDExpectations = arrayOf("invalid-id", "valid-id")
val presetFindByIdReturns = arrayOf(null, mockk<Preset>(relaxed = true))
val playPresetCallCount = arrayOf(0, 1)
for (i in presetIDExpectations.indices) {
every { mockRepo.get(presetIDExpectations[i]) } returns presetFindByIdReturns[i]
Intents.init()
Intents.intending(hasComponent(MainActivity::class.qualifiedName))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
try {
Intent(ApplicationProvider.getApplicationContext(), ShortcutHandlerActivity::class.java)
.putExtra(ShortcutHandlerActivity.EXTRA_SHORTCUT_ID, presetIDExpectations[i])
.putExtra(ShortcutHandlerActivity.EXTRA_PRESET_ID, presetIDExpectations[i])
.also { ActivityScenario.launch<ShortcutHandlerActivity>(it) }
Intents.intended(
allOf(
hasComponent(MainActivity::class.qualifiedName),
hasExtra(MainActivity.EXTRA_NAV_DESTINATION, R.id.presets)
),
Intents.times(1)
)
verify(exactly = playPresetCallCount[i], timeout = 5000L) {
PlaybackController.playPreset(any(), presetIDExpectations[i])
}
} finally {
Intents.release()
}
}
}
}

View File

@ -0,0 +1,52 @@
package com.github.ashutoshgngwr.noice.fragment
import android.content.Intent
import android.net.Uri
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.filterEquals
import androidx.test.espresso.matcher.ViewMatchers.withChild
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.ashutoshgngwr.noice.R
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AboutFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<AboutFragment>
@Before
fun setup() {
fragmentScenario = launchFragmentInContainer()
}
@Test
fun testAboutItemClick() {
Intents.init()
// can't test everything. Picking one item at random
onView(withChild(withText(R.string.app_copyright))).perform(click())
intended(
filterEquals(
Intent(
Intent.ACTION_VIEW,
Uri.parse(
InstrumentationRegistry.getInstrumentation()
.targetContext
.getString(R.string.app_license_url)
)
)
)
)
Intents.release()
}
}

View File

@ -0,0 +1,169 @@
package com.github.ashutoshgngwr.noice.fragment
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.fragment.app.testing.withFragment
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.R
import io.mockk.every
import io.mockk.mockk
import org.hamcrest.Matchers.not
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.random.Random
@RunWith(AndroidJUnit4::class)
class DialogFragmentTest {
private lateinit var emptyFragmentScenario: FragmentScenario<Fragment>
@Before
fun setup() {
emptyFragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@Test
fun testTitleText() {
newDialog { title(R.string.app_name) }
EspressoX.onViewInDialog(withId(R.id.title), withText(R.string.app_name))
.check(matches(isDisplayed()))
}
@Test
fun testPositiveButton() {
newDialog { positiveButton(R.string.app_name) }
EspressoX.onViewInDialog(withId(R.id.positive), withText(R.string.app_name))
.perform(click())
onView(isRoot()).inRoot(not(isDialog()))
}
@Test
fun testNegativeButton() {
newDialog { negativeButton(R.string.app_name) }
EspressoX.onViewInDialog(withId(R.id.negative), withText(R.string.app_name))
.perform(click())
onView(isRoot()).inRoot(not(isDialog()))
}
@Test
fun testNeutralButton() {
newDialog { neutralButton(android.R.string.copy) }
EspressoX.onViewInDialog(withId(R.id.neutral), withText(android.R.string.copy))
.perform(click())
onView(isRoot()).inRoot(not(isDialog()))
}
@Test
fun testMessageText() {
newDialog { message(R.string.app_name) }
EspressoX.onViewInDialog(isDescendantOfA(withId(R.id.content)), withText(R.string.app_name))
.check(matches(isDisplayed()))
}
@Test
fun testTextInput() {
val mockValidator = mockk<(String) -> Int>()
every { mockValidator.invoke("invalid") } returns R.string.app_name
every { mockValidator.invoke("test") } returns 0
val dialogFragment = newDialog {
input(
hintRes = R.string.app_name,
preFillValue = "test",
validator = mockValidator
)
}
EspressoX.onViewInDialog(isDescendantOfA(withId(R.id.content)), withId(R.id.editText))
.check(matches(isDisplayed()))
.perform(replaceText("invalid"))
EspressoX.onViewInDialog(withId(R.id.textInputLayout))
.check(matches(EspressoX.withErrorText(R.string.app_name)))
EspressoX.onViewInDialog(withId(R.id.positive))
.check(matches(not(isEnabled())))
EspressoX.onViewInDialog(isDescendantOfA(withId(R.id.content)), withId(R.id.editText))
.perform(replaceText("test"))
EspressoX.onViewInDialog(withId(R.id.textInputLayout))
.check(matches(not(EspressoX.withErrorText(R.string.app_name))))
assertEquals("test", dialogFragment.getInputText())
}
@Test
fun testSingleChoiceList() {
var selectedItem = 0
val items = arrayOf("test-0", "test-1", "test-2")
newDialog {
singleChoiceItems(items, currentChoice = selectedItem) { choice ->
selectedItem = choice
}
}
items.forEach {
EspressoX.onViewInDialog(isDescendantOfA(withId(android.R.id.list)), withText(it))
.check(matches(isDisplayed()))
}
EspressoX.onViewInDialog(isDescendantOfA(withId(android.R.id.list)), withText(items[1]))
.perform(click())
onView(isRoot()).inRoot(not(isDialog()))
assertEquals(1, selectedItem)
}
@Test
fun testSlider() {
val id = View.generateViewId()
val expectedValue = Random.nextInt(10).toFloat()
var value = 1.0f
newDialog {
slider(
viewID = id,
from = 0.0f,
to = 10.0f,
value = value,
changeListener = { v -> value = v },
)
positiveButton(R.string.okay)
}
EspressoX.onViewInDialog(withId(id))
.check(matches(isDisplayed()))
.perform(EspressoX.slide(expectedValue))
EspressoX.onViewInDialog(withId(R.id.positive)).perform(click())
assertEquals(expectedValue, value)
}
private fun newDialog(options: DialogFragment.() -> Unit): DialogFragment {
val f = emptyFragmentScenario.withFragment {
DialogFragment.show(childFragmentManager, options)
}
// wait for dialog to be visible
EspressoX.onViewInDialog(withId(R.id.dialog_root))
.check(matches(isDisplayed()))
return f
}
}

View File

@ -0,0 +1,133 @@
package com.github.ashutoshgngwr.noice.fragment
import android.content.Context
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.preference.PreferenceManager
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.activity.AppIntroActivity
import com.github.ashutoshgngwr.noice.activity.MainActivity
import com.github.ashutoshgngwr.noice.model.Sound
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class HomeFragmentTest {
// activityScenario is more appropriate than FragmentScenario for two reasons.
// 1. Activity in fragment scenario doesn't have an action bar (for menu items)
// 2. NavController need to be manually injected in a fragment in fragment scenario.
private lateinit var activityScenario: ActivityScenario<MainActivity>
private lateinit var navController: NavController
@Before
fun setup() {
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit {
putBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, true)
putBoolean(MainActivity.PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, true)
putBoolean(MainActivity.PREF_HAS_SEEN_V2_ANNOUNCEMENT, true)
}
activityScenario = ActivityScenario.launch(MainActivity::class.java)
activityScenario.onActivity {
navController = it.findNavController(R.id.nav_host_fragment)
}
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testStartDestination() {
onView(withId(R.id.bottom_nav))
.check(matches(EspressoX.withBottomNavSelectedItem(R.id.library)))
withChildNavController {
assertEquals(R.id.library, it.currentDestination?.id)
}
mockkObject(SettingsRepository)
every { SettingsRepository.newInstance(any()) } returns mockk(relaxed = true) {
every { shouldDisplayPresetsAsHomeScreen() } returns true
}
setup() // haha!
onView(withId(R.id.bottom_nav))
.check(matches(EspressoX.withBottomNavSelectedItem(R.id.presets)))
withChildNavController {
assertEquals(R.id.presets, it.currentDestination?.id)
}
}
@Test
fun testPlaybackToggleMenuItem() {
onView(withId(R.id.action_pause))
.check(doesNotExist())
onView(withId(R.id.action_resume))
.check(doesNotExist())
// play a sound
val context = ApplicationProvider.getApplicationContext<Context>()
PlaybackController.play(context, Sound.LIBRARY.keys.first())
try {
onView(withId(R.id.action_pause))
.check(matches(isDisplayed()))
.perform(click())
onView(withId(R.id.action_pause))
.check(doesNotExist())
onView(withId(R.id.action_resume))
.check(matches(isDisplayed()))
.perform(click())
onView(withId(R.id.action_resume))
.check(doesNotExist())
} finally {
PlaybackController.stop(context)
}
}
private inline fun onHomeFragment(crossinline block: (HomeFragment) -> Unit) {
activityScenario.onActivity {
val parent = it.supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as Fragment
val home = parent.childFragmentManager.fragments.first() as HomeFragment
block.invoke(home)
}
}
private inline fun withChildNavController(crossinline block: (NavController) -> Unit) {
onHomeFragment {
val f = it.childFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
block.invoke(f.navController)
}
}
}

View File

@ -0,0 +1,355 @@
package com.github.ashutoshgngwr.noice.fragment
import android.support.v4.media.session.PlaybackStateCompat
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.MediaPlayerService
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.model.Preset
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.playback.Player
import com.github.ashutoshgngwr.noice.provider.ReviewFlowProvider
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import org.greenrobot.eventbus.EventBus
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.random.Random
@RunWith(AndroidJUnit4::class)
class LibraryFragmentTest {
private lateinit var mockEventBus: EventBus
private lateinit var mockPresetRepository: PresetRepository
private lateinit var mockSettingsRepository: SettingsRepository
private lateinit var mockReviewFlowProvider: ReviewFlowProvider
private lateinit var fragmentScenario: FragmentScenario<LibraryFragment>
@Before
fun setup() {
mockkStatic(EventBus::class)
mockkObject(
PlaybackController,
PresetRepository.Companion,
SettingsRepository.Companion
)
mockReviewFlowProvider = mockk(relaxed = true)
ApplicationProvider.getApplicationContext<NoiceApplication>()
.reviewFlowProvider = mockReviewFlowProvider
mockEventBus = mockk(relaxed = true)
mockPresetRepository = mockk(relaxed = true)
mockSettingsRepository = mockk(relaxed = true)
every { EventBus.getDefault() } returns mockEventBus
every { PresetRepository.newInstance(any()) } returns mockPresetRepository
every { SettingsRepository.newInstance(any()) } returns mockSettingsRepository
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testRecyclerViewItem_playButton() {
// stub the real implementation
every { PlaybackController.play(any(), any()) } returns Unit
onView(withId(R.id.sound_list)).perform(
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
click()
)
)
verify(exactly = 1) { PlaybackController.play(any(), "birds") }
}
@Test
fun testRecyclerViewItem_stopButton() {
every { PlaybackController.stop(any(), any()) } returns Unit
val mockUpdateEvent = mockk<MediaPlayerService.PlaybackUpdateEvent>(relaxed = true) {
every { players } returns hashMapOf("birds" to mockk(relaxed = true))
}
fragmentScenario.onFragment { it.onPlayerManagerUpdate(mockUpdateEvent) }
onView(withId(R.id.sound_list)).perform(
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
allOf(
hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
hasDescendant(
allOf(withId(R.id.play_indicator), withEffectiveVisibility(Visibility.VISIBLE))
)
),
click()
)
)
verify(exactly = 1) { PlaybackController.stop(any(), "birds") }
}
@Test
fun testRecyclerViewItem_volumeSlider() {
val mockPlayer = mockk<Player>(relaxed = true) {
every { volume } returns Player.DEFAULT_VOLUME
}
val mockUpdateEvent = mockk<MediaPlayerService.PlaybackUpdateEvent>(relaxed = true) {
every { players } returns hashMapOf("birds" to mockPlayer)
}
every {
mockEventBus.getStickyEvent(MediaPlayerService.PlaybackUpdateEvent::class.java)
} returns mockUpdateEvent
fragmentScenario.onFragment { it.onPlayerManagerUpdate(mockUpdateEvent) }
val expectedVolumes = arrayOf(0, Player.MAX_VOLUME, 5)
for (expectedVolume in expectedVolumes) {
onView(withId(R.id.sound_list)).perform(
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
EspressoX.clickInItem(R.id.volume_button)
)
)
EspressoX.onViewInDialog(withId(R.id.volume_slider))
.check(matches(isDisplayed()))
.perform(EspressoX.slide(expectedVolume.toFloat()))
EspressoX.onViewInDialog(withId(R.id.positive)).perform(click())
verify(exactly = 1) { mockPlayer.setVolume(expectedVolume) }
}
}
@Test
fun testRecyclerViewItem_timePeriodSlider() {
val mockPlayer = mockk<Player>(relaxed = true) {
every { timePeriod } returns Player.DEFAULT_TIME_PERIOD
}
val mockUpdateEvent = mockk<MediaPlayerService.PlaybackUpdateEvent>(relaxed = true) {
every { players } returns hashMapOf("rolling_thunder" to mockPlayer)
}
every {
mockEventBus.getStickyEvent(MediaPlayerService.PlaybackUpdateEvent::class.java)
} returns mockUpdateEvent
fragmentScenario.onFragment { it.onPlayerManagerUpdate(mockUpdateEvent) }
val expectedTimePeriods = arrayOf(
Player.MIN_TIME_PERIOD,
Player.MAX_TIME_PERIOD,
// following because step size of the slider is 10s
Random.nextInt((Player.DEFAULT_TIME_PERIOD / 10) + 1, Player.MAX_TIME_PERIOD / 10) * 10
)
for (expectedTimePeriod in expectedTimePeriods) {
onView(withId(R.id.sound_list))
.perform(
RecyclerViewActions.scrollTo<RecyclerView.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText(R.string.rolling_thunder)))
),
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText(R.string.rolling_thunder))),
EspressoX.clickInItem(R.id.time_period_button)
)
)
EspressoX.onViewInDialog(withId(R.id.time_period_slider))
.check(matches(isDisplayed()))
.perform(EspressoX.slide(expectedTimePeriod.toFloat()))
EspressoX.onViewInDialog(withId(R.id.positive)).perform(click())
verify(exactly = 1) { mockPlayer.timePeriod = expectedTimePeriod }
}
}
@Test
fun testSavePresetButton_onUnknownPresetPlayback() {
val mockUpdateEvent = mockk<MediaPlayerService.PlaybackUpdateEvent>(relaxed = true) {
every { players } returns mockk(relaxed = true)
}
val states = arrayOf(
PlaybackStateCompat.STATE_PLAYING,
PlaybackStateCompat.STATE_PAUSED,
PlaybackStateCompat.STATE_STOPPED
)
val visibility = arrayOf(
Visibility.VISIBLE,
Visibility.GONE,
Visibility.GONE,
)
for (i in states.indices) {
every { mockUpdateEvent.state } returns states[i]
fragmentScenario.onFragment {
it.onPlayerManagerUpdate(mockUpdateEvent)
}
onView(withId(R.id.save_preset_button))
.check(matches(withEffectiveVisibility(visibility[i])))
}
}
@Test
fun testSavePresetButton_onKnownPresetPlayback() {
val mockPlayers: Map<String, Player> = hashMapOf(
"birds" to mockk(relaxed = true),
"rolling_thunder" to mockk(relaxed = true)
)
val preset = Preset.from("test", mockPlayers.values)
mockkObject(Preset.Companion)
every { Preset.from("", mockPlayers.values) } returns preset
every { mockPresetRepository.list() } returns arrayOf(preset)
fragmentScenario.onFragment { fragment ->
fragment.onPlayerManagerUpdate(mockk(relaxed = true) {
every { state } returns PlaybackStateCompat.STATE_PLAYING
every { players } returns mockPlayers
})
}
onView(withId(R.id.save_preset_button))
.check(matches(withEffectiveVisibility(Visibility.GONE)))
// when volume/time period slider is adjusted, save preset button should be visible.
// since the Sticky Event is mocked, the item being slided will perform a mock call. So we'll
// need to return a different instance of events (with expected value) when other components
// request it after sliding action happens.
every {
mockEventBus.getStickyEvent(MediaPlayerService.PlaybackUpdateEvent::class.java)
} returns mockk(relaxed = true) {
every { state } returns PlaybackStateCompat.STATE_PLAYING
every { players } returns hashMapOf(
"birds" to mockk(relaxed = true) {
every { volume } returns 6
},
"rolling_thunder" to mockk(relaxed = true)
)
}
onView(withId(R.id.sound_list)).perform(
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
EspressoX.clickInItem(R.id.volume_button)
)
)
EspressoX.onViewInDialog(withId(R.id.volume_slider))
.check(matches(isDisplayed()))
.perform(EspressoX.slide(6f))
EspressoX.onViewInDialog(withId(R.id.positive)).perform(click())
verify(exactly = 1) { requireNotNull(mockPlayers["birds"]).setVolume(6) }
onView(allOf(withId(R.id.save_preset_button), withEffectiveVisibility(Visibility.VISIBLE)))
}
@Test
fun testSavePresetButton_onClick() {
val mockPlayers: Map<String, Player> = hashMapOf(
"birds" to mockk(relaxed = true) {
every { soundKey } returns "birds"
every { volume } returns 1
every { timePeriod } returns Player.MIN_TIME_PERIOD + 2
},
"rolling_thunder" to mockk(relaxed = true) {
every { soundKey } returns "rolling_thunder"
every { volume } returns 3
every { timePeriod } returns Player.MIN_TIME_PERIOD + 4
}
)
every { mockPresetRepository.list() } returns arrayOf(
mockk(relaxed = true) {
every { name } returns "test-exists"
}
)
fragmentScenario.onFragment { fragment ->
fragment.onPlayerManagerUpdate(mockk(relaxed = true) {
every { state } returns PlaybackStateCompat.STATE_PLAYING
every { players } returns mockPlayers
})
}
onView(withId(R.id.save_preset_button))
.check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
.perform(click())
// should disable save button for duplicate names
EspressoX.onViewInDialog(withId(R.id.editText))
.check(matches(isDisplayed()))
.perform(replaceText("test-exists"))
EspressoX.onViewInDialog(withId(R.id.positive), withText(R.string.save))
.check(matches(not(isEnabled())))
EspressoX.onViewInDialog(withId(R.id.editText))
.perform(replaceText("test-does-not-exists"))
EspressoX.onViewInDialog(withId(R.id.positive), withText(R.string.save))
.check(matches(isEnabled()))
.perform(click())
onView(withId(R.id.save_preset_button)).check(matches(not(isDisplayed())))
val presetSlot = slot<Preset>()
verify { mockPresetRepository.create(capture(presetSlot)) }
for (playerState in presetSlot.captured.playerStates) {
assertEquals(mockPlayers[playerState.soundKey]?.volume, playerState.volume)
assertEquals(mockPlayers[playerState.soundKey]?.timePeriod, playerState.timePeriod)
}
verify(exactly = 1) { mockReviewFlowProvider.maybeAskForReview(any()) }
}
@Test
fun testShouldDisplaySoundIcons() {
val inputs = arrayOf(false, true)
val outputs = arrayOf(Visibility.GONE, Visibility.VISIBLE)
for (i in inputs.indices) {
every { mockSettingsRepository.shouldDisplaySoundIcons() } returns inputs[i]
fragmentScenario.recreate()
onView(withId(R.id.sound_list))
.perform(
RecyclerViewActions.actionOnItem<RecyclerView.ViewHolder>(
allOf(
hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
hasDescendant(allOf(withId(R.id.icon), withEffectiveVisibility(outputs[i])))
),
EspressoX.noop()
),
)
}
}
}

View File

@ -0,0 +1,358 @@
package com.github.ashutoshgngwr.noice.fragment
import android.content.Intent
import android.net.Uri
import android.support.v4.media.session.PlaybackStateCompat
import android.widget.Button
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasAction
import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.activity.ShortcutHandlerActivity
import com.github.ashutoshgngwr.noice.model.Preset
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.playback.Player
import com.github.ashutoshgngwr.noice.provider.ReviewFlowProvider
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import io.mockk.clearStaticMockk
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PresetsFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<PresetsFragment>
private lateinit var mockPreset: Preset
private lateinit var mockPresetRepository: PresetRepository
private lateinit var mockReviewFlowProvider: ReviewFlowProvider
@Before
fun setup() {
mockkStatic(ShortcutManagerCompat::class)
mockkObject(
Preset.Companion,
PlaybackController,
PresetRepository.Companion
)
mockReviewFlowProvider = mockk(relaxed = true)
ApplicationProvider.getApplicationContext<NoiceApplication>()
.reviewFlowProvider = mockReviewFlowProvider
mockPreset = mockk(relaxed = true) {
every { id } returns "test-id"
every { name } returns "test"
every { playerStates } returns arrayOf(
Preset.PlayerState("test-1", Player.DEFAULT_VOLUME, Player.DEFAULT_TIME_PERIOD),
Preset.PlayerState("test-2", Player.MAX_VOLUME, Player.MAX_TIME_PERIOD)
)
}
mockPresetRepository = mockk {
every { list() } returns arrayOf(mockPreset, mockk(relaxed = true) {
every { name } returns "test-exists"
})
}
every { PresetRepository.newInstance(any()) } returns mockPresetRepository
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testInitialLayout() {
onView(withId(R.id.empty_list_hint))
.check(matches(withEffectiveVisibility(Visibility.GONE)))
every { mockPresetRepository.list() } returns arrayOf()
fragmentScenario.recreate()
onView(withId(R.id.empty_list_hint))
.check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
}
@Test
fun testRecyclerViewItem_playButton() {
// stub the original method. Without stubbing, mockk will also run the real implementation.
every { PlaybackController.playPreset(any(), any()) } returns Unit
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.play_button)
)
)
verify(exactly = 1) { PlaybackController.playPreset(any(), "test-id") }
}
@Test
fun testRecyclerViewItem_stopButton() {
// ensure that PresetsFragment assumes it is playing a preset
every { Preset.from(any(), any()) } returns mockPreset
fragmentScenario.onFragment {
it.onPlayerManagerUpdate(mockk(relaxed = true) {
every { state } returns PlaybackStateCompat.STATE_PLAYING
})
}
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.play_button)
)
)
verify(exactly = 1) { PlaybackController.stop(any()) }
}
@Test
fun testRecyclerViewItem_shareOption() {
val presetUri = "test-preset-uri"
every { mockPreset.toUri() } returns Uri.parse(presetUri)
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
try {
Intents.init()
onView(withText(R.string.share)).perform(click()) // select share option
intended(
EspressoX.hasIntentChooser(
allOf(
hasAction(Intent.ACTION_SEND),
hasExtra(Intent.EXTRA_TEXT, presetUri)
)
)
)
} finally {
Intents.release()
}
}
@Test
fun testRecyclerViewItem_deleteOption() {
every { mockPresetRepository.delete(any()) } returns true
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.delete)).perform(click()) // select delete option
onView(allOf(instanceOf(Button::class.java), withText(R.string.delete)))
.perform(click()) // click delete button in confirmation dialog
onView(withText("test")).check(doesNotExist())
verify(exactly = 1) {
mockPresetRepository.delete("test-id")
ShortcutManagerCompat.removeDynamicShortcuts(any(), listOf("test-id"))
mockReviewFlowProvider.maybeAskForReview(any())
}
}
@Test
fun testRecyclerViewItem_deleteOption_onPresetPlaying() {
// ensure that PresetsFragment assumes it is playing a preset
every { Preset.from(any(), any()) } returns mockPreset
every { mockPresetRepository.delete(any()) } returns true
fragmentScenario.onFragment {
it.onPlayerManagerUpdate(mockk(relaxed = true) {
every { state } returns PlaybackStateCompat.STATE_PLAYING
})
}
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.delete)).perform(click()) // select delete option
onView(allOf(instanceOf(Button::class.java), withText(R.string.delete)))
.perform(click()) // click delete button in confirmation dialog
// should publish a stop playback event if preset was playing
verify(exactly = 1) { PlaybackController.stop(any()) }
}
@Test
fun testRecyclerViewItem_renameOption() {
every { mockPresetRepository.update(any()) } returns Unit
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.rename)).perform(click()) // select rename option
onView(withId(R.id.editText))
.check(matches(isDisplayed())) // check if the rename dialog was displayed
.perform(replaceText("test-exists")) // replace text in input field
onView(allOf(instanceOf(Button::class.java), withText(R.string.save)))
.check(matches(not(isEnabled())))
onView(withId(R.id.editText))
.check(matches(isDisplayed()))
.perform(replaceText("test-does-not-exists"))
onView(allOf(instanceOf(Button::class.java), withText(R.string.save)))
.check(matches(isEnabled()))
.perform(click()) // click on positive button
val presetSlot = slot<Preset>()
verify(exactly = 1) {
mockPreset.name = "test-does-not-exists"
mockPresetRepository.update(capture(presetSlot))
mockReviewFlowProvider.maybeAskForReview(any())
}
assertEquals(mockPreset, presetSlot.captured)
}
@Test
fun testRecyclerViewItem_AddToHomeScreenOption() {
val pinShortcutSupportedExpectations = arrayOf(false, true)
val expectedRequestPinShortcutCalls = arrayOf(0, 1)
for (i in pinShortcutSupportedExpectations.indices) {
// prevent system dialog from showing up.
every { ShortcutManagerCompat.requestPinShortcut(any(), any(), any()) } returns true
every {
ShortcutManagerCompat.isRequestPinShortcutSupported(any())
} returns pinShortcutSupportedExpectations[i]
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.add_to_home_screen)).perform(click()) // select add to home screen option
val shortcutInfoSlot = slot<ShortcutInfoCompat>()
verify(exactly = expectedRequestPinShortcutCalls[i]) {
ShortcutManagerCompat.requestPinShortcut(any(), capture(shortcutInfoSlot), any())
}
if (pinShortcutSupportedExpectations[i]) {
assertTrue(
"should capture a ShortcutInfo from requestPinShortcut() call",
shortcutInfoSlot.isCaptured
)
assertNotNull(shortcutInfoSlot.captured.id)
assertEquals("test", shortcutInfoSlot.captured.shortLabel)
val intent = shortcutInfoSlot.captured.intent
assertEquals(ShortcutHandlerActivity::class.qualifiedName, intent.component?.className)
assertNotNull(intent.getStringExtra(ShortcutHandlerActivity.EXTRA_SHORTCUT_ID))
assertEquals("test-id", intent.getStringExtra(ShortcutHandlerActivity.EXTRA_PRESET_ID))
} else {
assertFalse(
"should not capture a ShortcutInfo from requestPinShortcut() call",
shortcutInfoSlot.isCaptured
)
onView(withId(com.google.android.material.R.id.snackbar_text))
.check(matches(withText(R.string.pinned_shortcuts_not_supported)))
}
clearStaticMockk(ShortcutManagerCompat::class)
}
}
@Test
fun testRecyclerViewItem_addToAppShortcuts() {
every { ShortcutManagerCompat.addDynamicShortcuts(any(), any()) } returns true
every { ShortcutManagerCompat.getDynamicShortcuts(any()) } returns mutableListOf()
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.add_to_app_shortcuts)).perform(click())
val shortcutInfoSlot = slot<List<ShortcutInfoCompat>>()
verify(exactly = 1) {
ShortcutManagerCompat.addDynamicShortcuts(any(), capture(shortcutInfoSlot))
}
assertEquals(1, shortcutInfoSlot.captured.size)
assertEquals("test-id", shortcutInfoSlot.captured[0].id)
}
@Test
fun testRecyclerViewItem_removeFromAppShortcuts() {
every { ShortcutManagerCompat.getDynamicShortcuts(any()) } returns listOf(
mockk(relaxed = true) {
every { id } returns mockPreset.id
}
)
// open context menu
onView(withId(R.id.list)).perform(
RecyclerViewActions.actionOnItem<PresetsFragment.ViewHolder>(
hasDescendant(allOf(withId(R.id.title), withText("test"))),
EspressoX.clickInItem(R.id.menu_button)
)
)
onView(withText(R.string.remove_from_app_shortcuts)).perform(click())
verify(exactly = 1) {
ShortcutManagerCompat.removeDynamicShortcuts(any(), listOf("test-id"))
}
}
}

View File

@ -0,0 +1,71 @@
package com.github.ashutoshgngwr.noice.fragment
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.model.Sound
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RandomPresetFragmentTest {
@Before
fun setup() {
mockkObject(PlaybackController)
every { PlaybackController.playRandomPreset(any(), any(), any()) } returns Unit
ApplicationProvider.getApplicationContext<NoiceApplication>()
.reviewFlowProvider = mockk(relaxed = true)
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testRandomPresetButton_onClick() {
val intensities = mapOf(
R.id.preset_intensity__any to RandomPresetFragment.RANGE_INTENSITY_ANY,
R.id.preset_intensity__dense to RandomPresetFragment.RANGE_INTENSITY_DENSE,
R.id.preset_intensity__light to RandomPresetFragment.RANGE_INTENSITY_LIGHT
)
val types = mapOf(
R.id.preset_type__any to null,
R.id.preset_type__focus to Sound.Tag.FOCUS,
R.id.preset_type__relax to Sound.Tag.RELAX
)
launchFragmentInContainer<RandomPresetFragment>(null, R.style.Theme_App)
val intensityID = intensities.keys.random()
val typeID = types.keys.random()
onView(withId(typeID)).perform(ViewActions.click())
onView(withId(intensityID)).perform(ViewActions.click())
onView(withId(R.id.play_button))
.perform(ViewActions.click())
verify(exactly = 1) {
PlaybackController.playRandomPreset(
any(), types[typeID],
intensities[intensityID] ?: IntRange.EMPTY
)
}
}
}

View File

@ -0,0 +1,143 @@
package com.github.ashutoshgngwr.noice.fragment
import android.content.Context
import android.net.Uri
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import java.io.InputStream
import java.io.OutputStream
@RunWith(AndroidJUnit4::class)
class SettingsFragmentTest {
private lateinit var mockPresetRepository: PresetRepository
private lateinit var fragmentScenario: FragmentScenario<SettingsFragment>
@Before
fun setup() {
mockPresetRepository = mockk()
mockkObject(PresetRepository)
every { PresetRepository.newInstance(any()) } returns mockPresetRepository
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@Test
fun testExportPresets() {
val exportData = "test-preset-data"
every { mockPresetRepository.writeTo(any()) } answers {
firstArg<OutputStream>().write(exportData.toByteArray())
}
// skipping the part where we click the preference and then select a file
val file = File.createTempFile(
"test-export",
null,
ApplicationProvider.getApplicationContext<Context>().cacheDir
)
try {
fragmentScenario.onFragment { it.onCreateDocumentResult(Uri.fromFile(file)) }
assertEquals(exportData, file.readText())
} finally {
file.delete()
}
}
@Test
fun testImportPresets() {
val importData = "test-preset-data"
every { mockPresetRepository.readFrom(any()) } answers {
assertEquals(importData, firstArg<InputStream>().readBytes().decodeToString())
}
val file = File.createTempFile(
"test-export",
null,
ApplicationProvider.getApplicationContext<Context>().cacheDir
)
try {
file.writeText(importData)
fragmentScenario.onFragment { it.onOpenDocumentResult(Uri.fromFile(file)) }
verify(exactly = 1) { mockPresetRepository.readFrom(any()) }
} finally {
file.delete()
}
}
@Test
fun testRemoveAllAppShortcuts() {
mockkStatic(ShortcutManagerCompat::class)
onView(withId(androidx.preference.R.id.recycler_view))
.perform(
RecyclerViewActions.actionOnItem<androidx.preference.PreferenceViewHolder>(
hasDescendant(withText(R.string.remove_all_app_shortcuts)), click()
)
)
EspressoX.onViewInDialog(withId(R.id.positive))
.perform(click())
verify(exactly = 1) { ShortcutManagerCompat.removeAllDynamicShortcuts(any()) }
}
@Test
fun testAppThemePreference() {
val nightModes = arrayOf(
AppCompatDelegate.MODE_NIGHT_NO,
AppCompatDelegate.MODE_NIGHT_YES,
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
)
val prefSummary = arrayOf(
R.string.app_theme_light,
R.string.app_theme_dark,
R.string.app_theme_system_default
)
val context = ApplicationProvider.getApplicationContext<Context>()
val themes = context.resources.getStringArray(R.array.app_themes)
val repo = SettingsRepository.newInstance(context)
for (i in themes.indices) {
onView(withId(androidx.preference.R.id.recycler_view))
.perform(
RecyclerViewActions.actionOnItem<androidx.preference.PreferenceViewHolder>(
hasDescendant(withText(R.string.app_theme)), click()
)
)
EspressoX.onViewInDialog(withText(themes[i]))
.check(matches(isDisplayed()))
.perform(click())
// wait for activity to be recreated.
onView(withText(R.string.app_theme)).check(matches(isDisplayed()))
onView(withText(prefSummary[i])).check(matches(isDisplayed()))
assertEquals(nightModes[i], repo.getAppThemeAsNightMode())
}
}
}

View File

@ -0,0 +1,99 @@
package com.github.ashutoshgngwr.noice.fragment
import android.os.SystemClock
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.EspressoX
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.databinding.SleepTimerFragmentBinding
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
@RunWith(AndroidJUnit4::class)
class SleepTimerFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<SleepTimerFragment>
@Before
fun setup() {
mockkObject(PlaybackController)
every { PlaybackController.scheduleAutoStop(any(), any()) } returns Unit
ApplicationProvider.getApplicationContext<NoiceApplication>()
.reviewFlowProvider = mockk(relaxed = true)
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@After
fun teardown() {
unmockkAll()
}
@Test
fun testDurationPickerListener_onSleepPreScheduled() {
val before = SystemClock.uptimeMillis()
every { PlaybackController.getScheduledAutoStopRemainingDurationMillis(any()) } returns 60L * 1000
onView(withId(R.id.duration_picker)).perform(EspressoX.addDurationToPicker(60))
verify(exactly = 1) {
PlaybackController.scheduleAutoStop(any(), withArg {
val delta = SystemClock.uptimeMillis() - before
val duration = TimeUnit.SECONDS.toMillis(120)
assertTrue(it in (duration - delta)..(duration))
})
}
}
@Test
fun testDurationPickerListener() {
val before = SystemClock.uptimeMillis()
onView(withId(R.id.duration_picker)).perform(EspressoX.addDurationToPicker(300))
verify(exactly = 1) {
PlaybackController.scheduleAutoStop(any(), withArg {
val delta = SystemClock.uptimeMillis() - before
val duration = TimeUnit.SECONDS.toMillis(300)
assertTrue(it in (duration - delta)..(duration))
})
}
}
@Test
fun testResetButton_shouldNotBeEnabledByDefault() {
onView(EspressoX.withDurationPickerResetButton(withId(R.id.duration_picker)))
.check(matches(not(isEnabled())))
}
@Test
fun testResetButton_onAutoSleepScheduled() {
fragmentScenario.onFragment {
SleepTimerFragmentBinding.bind(it.requireView()).also { binding ->
binding.durationPicker.setResetButtonEnabled(true)
}
}
onView(EspressoX.withDurationPickerResetButton(withId(R.id.duration_picker)))
.perform(scrollTo(), click())
onView(withText(R.string.auto_sleep_schedule_cancelled)).check(matches(isDisplayed()))
verify(exactly = 1) { PlaybackController.clearScheduledAutoStop(any()) }
}
}

View File

@ -0,0 +1,45 @@
package com.github.ashutoshgngwr.noice.fragment
import android.content.Intent
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.matcher.IntentMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.R
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SupportDevelopmentFragmentTest {
private lateinit var fragmentScenario: FragmentScenario<SupportDevelopmentFragment>
@Before
fun setup() {
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
Intents.init()
}
@After
fun teardown() {
Intents.release()
}
@Test
fun testShareWithFriendsButton() {
onView(withId(R.id.share_button)).perform(scrollTo(), click())
Intents.intended(
IntentMatchers.filterEquals(
Intent(Intent.ACTION_CHOOSER)
)
)
}
}

View File

@ -0,0 +1,274 @@
package com.github.ashutoshgngwr.noice.fragment
import android.icu.util.Calendar
import androidx.core.content.edit
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.preference.PreferenceManager
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.PickerActions
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.WakeUpTimerManager
import com.github.ashutoshgngwr.noice.model.Preset
import com.github.ashutoshgngwr.noice.provider.ReviewFlowProvider
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import io.mockk.clearMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class WakeUpTimerFragmentTest {
private lateinit var mockPresetRepository: PresetRepository
private lateinit var mockReviewFlowProvider: ReviewFlowProvider
private lateinit var fragmentScenario: FragmentScenario<WakeUpTimerFragment>
@Before
fun setup() {
mockkObject(PresetRepository.Companion, WakeUpTimerManager)
mockReviewFlowProvider = mockk(relaxed = true)
ApplicationProvider.getApplicationContext<NoiceApplication>()
.reviewFlowProvider = mockReviewFlowProvider
mockPresetRepository = mockk {
every { get(null) } returns null
every { list() } returns emptyArray()
}
every { PresetRepository.newInstance(any()) } returns mockPresetRepository
every { WakeUpTimerManager.set(any(), any()) } returns Unit
fragmentScenario = launchFragmentInContainer(null, R.style.Theme_App)
}
@After
fun teardown() {
unmockkAll()
with(PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())) {
edit { clear() }
}
}
@Test
fun testInitialLayout_whenTimerIsNotPreScheduled() {
onView(withId(R.id.select_preset_button))
.check(matches(isEnabled()))
.check(matches(withText(R.string.select_preset)))
onView(withId(R.id.set_time_button))
.check(matches(not(isEnabled())))
onView(withId(R.id.reset_time_button))
.check(matches(not(isEnabled())))
}
@Test
fun testInitialLayout_whenTimerIsPreScheduled() {
val expectedPresetID = "test-preset-id"
val expectedPresetName = "test-preset-name"
every { mockPresetRepository.get(expectedPresetID) } returns mockk {
every { name } returns expectedPresetName
}
every { WakeUpTimerManager.get(any()) } returns mockk {
every { presetID } returns expectedPresetID
every { atMillis } returns System.currentTimeMillis() + 10000L
}
// fragmentScenario.recreate() // for whatever reasons, doesn't invoke Fragment.onViewCreated().
fragmentScenario.onFragment { it.onViewCreated(it.requireView(), null) }
onView(withId(R.id.select_preset_button))
.check(matches(isEnabled()))
.check(matches(withText(expectedPresetName)))
onView(withId(R.id.set_time_button))
.check(matches(isEnabled()))
onView(withId(R.id.reset_time_button))
.check(matches(isEnabled()))
}
@Test
fun testInitialLayout_whenTimerIsPreScheduled_andPresetIsDeletedFromStorage() {
every { mockPresetRepository.get("test") } returns null
every { WakeUpTimerManager.get(any()) } returns mockk {
every { presetID } returns "test"
every { atMillis } returns System.currentTimeMillis() + 10000L
}
fragmentScenario.recreate()
onView(withId(R.id.select_preset_button))
.check(matches(isEnabled()))
.check(matches(withText(R.string.select_preset)))
onView(withId(R.id.set_time_button))
.check(matches(not(isEnabled())))
onView(withId(R.id.reset_time_button))
.check(matches(not(isEnabled())))
}
@Test
fun testSelectPreset_withoutPresets() {
every { mockPresetRepository.list() } returns arrayOf()
onView(withId(R.id.select_preset_button))
.check(matches(withText(R.string.select_preset)))
.perform(click())
onView(withText(R.string.preset_info__description))
.check(matches(isDisplayed()))
}
@Test
fun testSetTimer() {
val savedPreset = mockk<Preset>(relaxed = true) {
every { id } returns "test-id-1"
every { name } returns "test-1"
}
every { mockPresetRepository.get("test-id-1") } returns savedPreset
every { mockPresetRepository.list() } returns arrayOf(
savedPreset,
mockk(relaxed = true) {
every { id } returns "test-id-2"
every { name } returns "test-2"
}
)
onView(withId(R.id.select_preset_button))
.perform(click())
onView(withId(android.R.id.list))
.check(matches(withChild(withText("test-1"))))
.check(matches(withChild(withText("test-2"))))
onView(withText("test-1"))
.perform(click())
onView(withId(R.id.select_preset_button))
.check(matches(withText("test-1")))
verify(exactly = 0) { WakeUpTimerManager.set(any(), any()) }
onView(withId(R.id.time_picker))
.perform(PickerActions.setTime(1, 2))
onView(withId(R.id.set_time_button))
.check(matches(isEnabled()))
.perform(scrollTo(), click())
val calendar = Calendar.getInstance()
val timerSlot = slot<WakeUpTimerManager.Timer>()
try {
verify(exactly = 1) {
WakeUpTimerManager.set(any(), capture(timerSlot))
mockReviewFlowProvider.maybeAskForReview(any())
}
} finally {
clearMocks(WakeUpTimerManager, mockReviewFlowProvider)
}
calendar.timeInMillis = timerSlot.captured.atMillis
assertEquals(1, calendar.get(Calendar.HOUR_OF_DAY))
assertEquals(2, calendar.get(Calendar.MINUTE))
assertEquals("test-id-1", timerSlot.captured.presetID)
onView(withId(R.id.reset_time_button)).check(matches(isEnabled()))
onView(withSubstring("The alarm will go off in"))
.check(matches(isDisplayed()))
}
@Test
fun testCancelTimer() {
every { mockPresetRepository.get("test-id") } returns mockk {
every { name } returns "test-name"
}
every { WakeUpTimerManager.get(any()) } returns mockk {
every { presetID } returns "test-id"
every { atMillis } returns System.currentTimeMillis() + 10000L
}
fragmentScenario.recreate()
clearMocks(WakeUpTimerManager)
onView(withId(R.id.reset_time_button))
.check(matches(isEnabled()))
.perform(scrollTo(), click())
verify(exactly = 1) { WakeUpTimerManager.cancel(any()) }
}
@Test
fun testLoadPreset() {
val savedPresetID = "test-saved-preset-id"
val savedPreset = mockk<Preset>(relaxed = true) {
every { id } returns savedPresetID
every { name } returns "test-saved-preset"
}
every { mockPresetRepository.list() } returns arrayOf(
mockk(relaxed = true) {
every { id } returns "test-not-saved-preset-id-1"
every { name } returns "test-not-saved-preset-1"
},
savedPreset,
mockk(relaxed = true) {
every { id } returns "test-not-saved-preset-id-2"
every { name } returns "test-not-saved-preset-2"
}
)
every { WakeUpTimerManager.getLastUsedPresetID(any()) } returns savedPresetID
every { mockPresetRepository.get(savedPresetID) } returns savedPreset
fragmentScenario.recreate()
onView(withId(R.id.select_preset_button))
.check(matches(withText("test-saved-preset")))
}
@Test
fun testNotSavedPreset_loadFirstPreset() {
val savedPresetID = "test-not-saved-preset-id-1"
val savedPreset = mockk<Preset>(relaxed = true) {
every { id } returns savedPresetID
every { name } returns "test-not-saved-preset-1"
}
every { mockPresetRepository.get(savedPresetID) } returns savedPreset
every { mockPresetRepository.list() } returns arrayOf(
savedPreset,
mockk(relaxed = true) {
every { id } returns "test-saved-preset-id"
every { name } returns "test-saved-preset"
},
mockk(relaxed = true) {
every { id } returns "test-not-saved-preset-id-2"
every { name } returns "test-not-saved-preset-2"
}
)
fragmentScenario.recreate()
onView(withId(R.id.select_preset_button))
.check(matches(withText("test-not-saved-preset-1")))
}
}

View File

@ -0,0 +1,250 @@
package com.github.ashutoshgngwr.noice
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.view.Menu
import android.view.MenuItem
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.scrollTo
import androidx.test.espresso.contrib.PickerActions
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItem
import androidx.test.espresso.contrib.RecyclerViewActions.actionOnItemAtPosition
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.github.ashutoshgngwr.noice.activity.AppIntroActivity
import com.github.ashutoshgngwr.noice.activity.MainActivity
import com.github.ashutoshgngwr.noice.fragment.PresetsFragment
import com.github.ashutoshgngwr.noice.playback.Player
import io.mockk.every
import io.mockk.mockk
import org.hamcrest.Matchers.allOf
import org.junit.After
import org.junit.AfterClass
import org.junit.Assume.assumeNotNull
import org.junit.BeforeClass
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestRule
import org.junit.runner.RunWith
import org.junit.runners.model.Statement
import tools.fastlane.screengrab.Screengrab
import tools.fastlane.screengrab.cleanstatusbar.CleanStatusBar
import tools.fastlane.screengrab.locale.LocaleTestRule
@RunWith(AndroidJUnit4::class)
class GenerateScreenshots {
companion object {
private const val IS_SCREENGRAB = "is_screengrab"
private const val SLEEP_PERIOD_BEFORE_SCREENGRAB = 500L
@JvmField
@ClassRule
val localeTestRule = LocaleTestRule()
@JvmStatic
@BeforeClass
fun setupAll() {
CleanStatusBar.enableWithDefaults()
// prevent app intro and data consent from showing up
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit {
clear() // clear any existing preferences.
putBoolean(AppIntroActivity.PREF_HAS_USER_SEEN_APP_INTRO, true)
putBoolean(MainActivity.PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, true)
}
}
@JvmStatic
@AfterClass
fun teardownAll() {
CleanStatusBar.disable()
// clear saved presets
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext())
.edit { clear() }
}
}
@JvmField
@Rule
var activityScenarioRule = ActivityScenarioRule(MainActivity::class.java)
@Rule
@JvmField
val screenshotRule = TestRule { base, _ ->
object : Statement() {
override fun evaluate() {
// Screengrabfile passes the following launch argument. The tests in this call won't run
// otherwise.
assumeNotNull(InstrumentationRegistry.getArguments().getString(IS_SCREENGRAB))
base.evaluate()
}
}
}
@After
fun after() {
activityScenarioRule.scenario.onActivity {
it.stopService(Intent(it, MediaPlayerService::class.java))
}
}
@Test
fun library() {
// add a fake Cast button since we can't make the real one appear on an emulator.
ApplicationProvider.getApplicationContext<NoiceApplication>().castAPIProvider =
mockk(relaxed = true) {
every { addMenuItem(any(), any(), any()) } answers {
secondArg<Menu>().add("fake-cast-button").apply {
setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)
setIcon(R.drawable.cast_ic_notification_small_icon)
iconTintList = ColorStateList.valueOf(
ApplicationProvider.getApplicationContext<Context>()
.getColor(R.color.action_menu_item)
)
}
}
}
activityScenarioRule.scenario.recreate()
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(allOf(withId(R.id.title), withText(R.string.light_rain))),
click()
)
)
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(allOf(withId(R.id.title), withText(R.string.light_rain))),
EspressoX.clickInItem(R.id.volume_button)
)
)
onView(withId(R.id.volume_slider))
.perform(EspressoX.slide(Player.MAX_VOLUME.toFloat() - Player.DEFAULT_VOLUME))
onView(withId(R.id.positive))
.perform(click())
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(
allOf(withId(R.id.title), withText(R.string.distant_thunder))
),
click()
)
)
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(allOf(withId(R.id.title), withText(R.string.distant_thunder))),
EspressoX.clickInItem(R.id.volume_button)
)
)
onView(withId(R.id.volume_slider))
.perform(EspressoX.slide(Player.MAX_VOLUME.toFloat()))
onView(withId(R.id.positive))
.perform(click())
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(allOf(withId(R.id.title), withText(R.string.distant_thunder))),
EspressoX.clickInItem(R.id.time_period_button)
)
)
onView(withId(R.id.time_period_slider))
.perform(EspressoX.slide(Player.MAX_TIME_PERIOD.toFloat() - 300))
onView(withId(R.id.positive))
.perform(click())
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("1")
}
@Test
fun presets() {
onView(withId(R.id.presets)).perform(click())
onView(withId(R.id.list))
.perform(
actionOnItemAtPosition<PresetsFragment.ViewHolder>(
1, EspressoX.clickInItem(R.id.play_button)
)
)
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("2")
}
@Test
fun wakeUpTimer() {
// cancel any previous alarms
WakeUpTimerManager.cancel(ApplicationProvider.getApplicationContext())
onView(withId(R.id.wake_up_timer)).perform(click())
onView(withId(R.id.time_picker))
.perform(PickerActions.setTime(12, 30))
onView(withId(R.id.set_time_button))
.perform(scrollTo(), click())
onView(withText(R.string.wake_up_timer_description))
.perform(scrollTo())
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("3")
}
@Test
fun sleepTimer() {
onView(withId(R.id.sound_list)).perform(
actionOnItem<RecyclerView.ViewHolder>(
ViewMatchers.hasDescendant(allOf(withId(R.id.title), withText(R.string.birds))),
click()
)
)
onView(withId(R.id.sleep_timer)).perform(click())
onView(withId(R.id.duration_picker)).perform(
EspressoX.addDurationToPicker(1800)
)
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("4")
}
@Test
fun about() {
openActionBarOverflowOrOptionsMenu(ApplicationProvider.getApplicationContext())
onView(withText(R.string.about)).perform(click())
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("5")
}
@Test
fun settingsItem() {
openActionBarOverflowOrOptionsMenu(ApplicationProvider.getApplicationContext())
onView(withText(R.string.settings)).perform(click())
Thread.sleep(SLEEP_PERIOD_BEFORE_SCREENGRAB)
Screengrab.screenshot("6")
}
}

View File

@ -0,0 +1,31 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- screengrab-permissions -->
<!-- Allows unlocking your device and activating its screen so UI tests can succeed -->
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Allows for storing and retrieving screenshots -->
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Allows changing locales -->
<uses-permission
android:name="android.permission.CHANGE_CONFIGURATION"
tools:ignore="ProtectedPermissions" />
<!-- Allows changing SystemUI demo mode -->
<uses-permission
android:name="android.permission.DUMP"
tools:ignore="ProtectedPermissions" />
<!-- /screengrab-permissions -->
<application tools:ignore="AllowBackup" />
</manifest>

View File

@ -0,0 +1,39 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name="com.github.ashutoshgngwr.noice.FullNoiceApplication"
tools:ignore="AllowBackup"
tools:replace="name">
<meta-data
android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.github.ashutoshgngwr.noice.provider.CastOptionsProvider" />
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
<meta-data
android:name="firebase_analytics_collection_enabled"
android:value="false" />
<meta-data
android:name="google_analytics_adid_collection_enabled"
android:value="false" />
<meta-data
android:name="google_analytics_ssaid_collection_enabled"
android:value="false" />
<meta-data
android:name="google_analytics_default_allow_ad_personalization_signals"
android:value="false" />
<meta-data
android:name="google_analytics_automatic_screen_reporting_enabled"
android:value="false" />
</application>
</manifest>

View File

@ -0,0 +1,41 @@
package com.github.ashutoshgngwr.noice
import com.github.ashutoshgngwr.noice.provider.InAppBillingDonateViewProvider
import com.github.ashutoshgngwr.noice.provider.PlaystoreReviewFlowProvider
import com.github.ashutoshgngwr.noice.provider.RealAnalyticsProvider
import com.github.ashutoshgngwr.noice.provider.RealBillingProvider
import com.github.ashutoshgngwr.noice.provider.RealCastAPIProvider
import com.github.ashutoshgngwr.noice.provider.RealCrashlyticsProvider
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.firebase.FirebaseApp
@Suppress("unused")
class FullNoiceApplication : NoiceApplication() {
override fun initProviders() {
super.initProviders()
FirebaseApp.initializeApp(this)
// crashlytics and analytics doesn't require Google Mobile Services to work.
crashlyticsProvider = RealCrashlyticsProvider
analyticsProvider = RealAnalyticsProvider
if (isGoogleMobileServicesAvailable()) {
castAPIProvider = RealCastAPIProvider(this)
reviewFlowProvider = PlaystoreReviewFlowProvider
billingProvider = RealBillingProvider
donateViewProvider = InAppBillingDonateViewProvider
}
}
override fun isGoogleMobileServicesAvailable(): Boolean {
val result = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
if (result != ConnectionResult.SUCCESS) {
return super.isGoogleMobileServicesAvailable()
}
return true
}
}

View File

@ -0,0 +1,76 @@
package com.github.ashutoshgngwr.noice.playback.strategy
import android.content.Context
import androidx.media.AudioAttributesCompat
import com.github.ashutoshgngwr.noice.model.Sound
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import com.google.android.gms.cast.framework.CastSession
import com.google.gson.GsonBuilder
import com.google.gson.annotations.Expose
/**
* [CastPlaybackStrategy] implements [PlaybackStrategy] that sends the control events
* to the cast receiver application.
*/
class CastPlaybackStrategy(
context: Context,
private val session: CastSession,
private val namespace: String,
private val sound: Sound
) : PlaybackStrategy {
companion object {
private const val ACTION_CREATE = "create"
private const val ACTION_PLAY = "play"
private const val ACTION_PAUSE = "pause"
private const val ACTION_STOP = "stop"
}
@Suppress("unused")
private class PlayerEvent(
@Expose val src: Array<String>,
@Expose val isLooping: Boolean,
@Expose val volume: Float,
@Expose val action: String?,
@Expose val fadeInDuration: Long,
)
var volume: Float = 0.0f
private set
private val gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
private val settingsRepository = SettingsRepository.newInstance(context)
init {
notifyChanges(ACTION_CREATE)
}
override fun setVolume(volume: Float) {
if (this.volume == volume) {
return
}
this.volume = volume
notifyChanges(null)
}
override fun play() {
notifyChanges(ACTION_PLAY)
}
override fun pause() {
notifyChanges(ACTION_PAUSE)
}
override fun stop() {
notifyChanges(ACTION_STOP)
}
override fun setAudioAttributes(attrs: AudioAttributesCompat) = Unit
private fun notifyChanges(action: String?) {
val fadeInDuration = settingsRepository.getSoundFadeInDurationMillis()
val event = PlayerEvent(sound.src, sound.isLooping, volume, action, fadeInDuration)
session.sendMessage(namespace, gson.toJson(event))
}
}

View File

@ -0,0 +1,21 @@
package com.github.ashutoshgngwr.noice.playback.strategy
import android.content.Context
import com.github.ashutoshgngwr.noice.model.Sound
import com.google.android.gms.cast.framework.CastSession
/**
* A [PlaybackStrategyFactory] for creating [PlaybackStrategy] instances that cast media using the Google
* Cast application framework.
*/
class CastPlaybackStrategyFactory internal constructor(
private val context: Context,
private val session: CastSession,
private val namespace: String
) : PlaybackStrategyFactory {
override fun newInstance(sound: Sound): PlaybackStrategy {
return CastPlaybackStrategy(context, session, namespace, sound)
}
}

View File

@ -0,0 +1,11 @@
package com.github.ashutoshgngwr.noice.provider
import android.view.ViewGroup
import com.github.ashutoshgngwr.noice.widget.InAppBillingDonateView
object InAppBillingDonateViewProvider : DonateViewProvider {
override fun addViewToParent(parent: ViewGroup) {
parent.addView(InAppBillingDonateView(parent.context))
}
}

View File

@ -0,0 +1,81 @@
package com.github.ashutoshgngwr.noice.provider
import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import androidx.fragment.app.FragmentActivity
import androidx.preference.PreferenceManager
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import com.google.android.play.core.review.ReviewManagerFactory
import java.util.concurrent.TimeUnit
/**
* [PlaystoreReviewFlowProvider] provides the Google Play Store In-App review flow. The review flow
* will not always be shown. All original quota restrictions apply from the API. Additionally
* [PlaystoreReviewFlowProvider] drops all request to display review flow within a week of a
* successful launch review flow API call (without guarantees that the flow was shown).
*/
object PlaystoreReviewFlowProvider : ReviewFlowProvider {
private val TAG = this::class.simpleName
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val PREF_LAST_SHOWN_ON = "last_shown_on"
private lateinit var reviewManager: ReviewManager
private lateinit var reviewInfo: ReviewInfo
/**
* [init] initializes the [ReviewManager] and requests the [ReviewInfo] from the [ReviewManager].
*/
override fun init(context: Context) {
reviewManager = ReviewManagerFactory.create(context)
reviewManager.requestReviewFlow()
.addOnFailureListener {
Log.w(TAG, "review flow request failed!", it)
}.addOnSuccessListener {
Log.d(TAG, "review flow request successful!")
reviewInfo = it
}
}
/**
* [maybeAskForReview] checks whether [ReviewInfo] has been initialized and whether user has
* successfully completed the review flow within past 7 days. If both conditions are false,
* it requests the Google Play API to launch the review flow.
*/
override fun maybeAskForReview(activity: FragmentActivity) {
if (!this::reviewInfo.isInitialized) {
Log.d(TAG, "review info isn't initialized. can not launch review flow!")
return
}
if (isShownWithinLastWeek(activity)) {
Log.d(TAG, "review flow was shown within last week. abandoning request!")
return
}
reviewManager.launchReviewFlow(activity, reviewInfo)
.addOnFailureListener {
Log.w(TAG, "failed to complete review flow!", it)
}
.addOnSuccessListener {
Log.d(TAG, "review flow successfully completed!")
updateLastSeenTimestamp(activity)
}
}
private fun updateLastSeenTimestamp(context: Context) {
PreferenceManager.getDefaultSharedPreferences(context).edit {
putLong(PREF_LAST_SHOWN_ON, System.currentTimeMillis())
}
}
private fun isShownWithinLastWeek(context: Context): Boolean {
val timestamp = PreferenceManager.getDefaultSharedPreferences(context)
.getLong(PREF_LAST_SHOWN_ON, 0)
return TimeUnit.DAYS.toMillis(7L) + timestamp > System.currentTimeMillis()
}
}

View File

@ -0,0 +1,83 @@
package com.github.ashutoshgngwr.noice.provider
import android.os.Bundle
import androidx.core.os.bundleOf
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.setConsent
import com.google.firebase.ktx.Firebase
import kotlin.reflect.KClass
/**
* [RealAnalyticsProvider] provides a real concrete implementation of the Firebase Analytics API.
*/
object RealAnalyticsProvider : AnalyticsProvider {
private val fa = Firebase.analytics
private val playerStartTimes = mutableMapOf<String, Long>()
private var playbackStartTime = -1L
private var castSessionStartTime = -1L
init {
fa.setConsent {
adStorage = FirebaseAnalytics.ConsentStatus.DENIED
analyticsStorage = FirebaseAnalytics.ConsentStatus.GRANTED
}
}
override fun setCollectionEnabled(e: Boolean) {
fa.setAnalyticsCollectionEnabled(e)
}
override fun setCurrentScreen(name: String, clazz: KClass<out Any>, params: Bundle) {
params.putString(FirebaseAnalytics.Param.SCREEN_NAME, name)
clazz.simpleName?.also {
params.putString(FirebaseAnalytics.Param.SCREEN_CLASS, it)
}
fa.logEvent(FirebaseAnalytics.Event.SCREEN_VIEW, params)
}
override fun logEvent(name: String, params: Bundle) {
fa.logEvent(name, params)
}
override fun logPlayerStartEvent(key: String) {
if (key !in playerStartTimes) {
playerStartTimes[key] = System.currentTimeMillis()
}
if (playbackStartTime <= 0) {
playbackStartTime = System.currentTimeMillis()
}
}
override fun logPlayerStopEvent(key: String) {
playerStartTimes.remove(key)?.also {
val params = bundleOf("sound_key" to key, "duration_ms" to System.currentTimeMillis() - it)
fa.logEvent("sound_session", params)
}
if (playerStartTimes.isEmpty() && playbackStartTime > 0) {
val duration = System.currentTimeMillis() - playbackStartTime
fa.logEvent("playback_session", bundleOf("duration_ms" to duration))
playbackStartTime = -1L
}
}
override fun logCastSessionStartEvent() {
castSessionStartTime = System.currentTimeMillis()
}
override fun logCastSessionEndEvent() {
if (castSessionStartTime <= 0) {
return
}
val params = bundleOf("duration_ms" to System.currentTimeMillis() - castSessionStartTime)
fa.logEvent("cast_session", params)
castSessionStartTime = -1
}
}

View File

@ -0,0 +1,379 @@
package com.github.ashutoshgngwr.noice.provider
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import android.util.Base64
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import androidx.core.os.HandlerCompat
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ConsumeParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.android.billingclient.api.consumePurchase
import com.android.billingclient.api.querySkuDetails
import com.github.ashutoshgngwr.noice.ext.getMutableStringSet
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.security.KeyFactory
import java.security.PublicKey
import java.security.Signature
import java.security.SignatureException
import java.security.spec.X509EncodedKeySpec
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resumeWithException
/**
* [RealBillingProvider] implements a thin wrapper around Google Play Billing v4 client library. It
* auto-acknowledges new purchases. It also handles state transition of pending purchases.
*/
object RealBillingProvider : BillingProvider, BillingClientStateListener {
private const val GOOGLE_PLAY_SECURITY_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkxR84" +
"yP6PFaAFqhgVtFzI4O1Ws/xFQjJOhKCCrnyfs59SXSLsSbWjdMikCB7xcJsSkhfsril5iK88UIKhBLUW3oe16LO7YMOS" +
"6xeH0s0LdxHnF1rdwr0WtFc41CjGFIMWFxkB27jft97Ycp72cASjmU3K/Jc0a2Qo3thrpZlJN+vwRzveaVUE73o/Fyzd" +
"Uqyu4e8IngKOXDqxkgz3XLmzTHsx6XmeLTQl1WFMhOi5FxoHD9AHVoyZzbkGCMdRJERvk+ziSXdGR9pRUtGVkv+h5v3f" +
"wfVqBYZC28TAz5w6wSRDFvUnIp52nQH52vdHf1mrwHbeniMUJzV5GoBaspTqQIDAQAB"
@VisibleForTesting
internal const val PREF_NAME = "RealBillingProviderPreferences"
@VisibleForTesting
internal const val PREF_UNCONSUMED_ORDERS = "unconsumed_orders"
private const val PREF_PENDING_ORDERS = "pending_orders"
private const val COROUTINE_SCOPE_NAME = "RealBillingProviderScope"
private val LOG_TAG = this::class.simpleName
private const val RECONNECT_DELAY_MS = 2L * 1000L + 500L
private const val RECONNECT_MAX_COUNT = 10
private val RECONNECT_CALLBACK_TOKEN = "${this::class.qualifiedName}.reconnectCallback"
private lateinit var client: BillingClient
private lateinit var prefs: SharedPreferences
private lateinit var defaultScope: CoroutineScope
private var purchaseListener: BillingProvider.PurchaseListener? = null
private var reconnectCount = 0
private val prefsMutex = Mutex()
private val handler = Handler(Looper.getMainLooper())
private val isConnecting = AtomicBoolean(false)
private val securityKey: PublicKey
init {
val decodedKey = Base64.decode(GOOGLE_PLAY_SECURITY_KEY, Base64.DEFAULT)
securityKey = KeyFactory.getInstance("RSA")
.generatePublic(X509EncodedKeySpec(decodedKey))
}
override fun onBillingSetupFinished(result: BillingResult) {
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
Log.w(LOG_TAG, "billing service connection failed: ${result.debugMessage}")
retryServiceConnection()
return
}
Log.d(LOG_TAG, "billing service connected")
isConnecting.set(false)
reconnectCount = 0
refreshPurchases()
}
override fun onBillingServiceDisconnected() = retryServiceConnection()
/**
* Implements service connection retry with constant delay [RECONNECT_DELAY_MS].
*/
private fun retryServiceConnection() {
if (reconnectCount >= RECONNECT_MAX_COUNT) {
isConnecting.set(false)
reconnectCount = 0
return
}
HandlerCompat.postDelayed(
handler, { client.startConnection(this) },
RECONNECT_CALLBACK_TOKEN, RECONNECT_DELAY_MS,
)
reconnectCount++
}
override fun init(context: Context, listener: BillingProvider.PurchaseListener?) {
purchaseListener = listener
defaultScope = CoroutineScope(Job() + CoroutineName(COROUTINE_SCOPE_NAME))
client = BillingClient.newBuilder(context)
.enablePendingPurchases()
.setListener { _, _ -> refreshPurchases() }
.build()
prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
Log.d(LOG_TAG, "init: startConnection")
isConnecting.set(true)
client.startConnection(this)
}
override fun close() {
handler.removeCallbacksAndMessages(RECONNECT_CALLBACK_TOKEN)
client.endConnection()
defaultScope.cancel()
Log.d(LOG_TAG, "close: end connection")
}
/**
* Query details of given [skus].
*
* @return List of [BillingProvider.SkuDetails] for provided [skus].
* @throws BillingProvider.QueryDetailsException when the query fails.
*/
@Throws(BillingProvider.QueryDetailsException::class)
override suspend fun queryDetails(
type: BillingProvider.SkuType,
skus: List<String>
): List<BillingProvider.SkuDetails> {
waitForBillingClientConnection()
if (!client.isReady) {
throw BillingProvider.QueryDetailsException("billing client is not ready")
}
val p = SkuDetailsParams.newBuilder()
.setSkusList(skus)
.setType(type.value)
.build()
val r = client.querySkuDetails(p)
if (r.billingResult.responseCode != BillingClient.BillingResponseCode.OK) {
throw BillingProvider.QueryDetailsException(r.billingResult.debugMessage)
}
return r.skuDetailsList?.map {
BillingProvider.SkuDetails(it.price, it.priceAmountMicros, it.originalJson)
} ?: throw BillingProvider.QueryDetailsException("sku details list is null")
}
/**
* Launch billing flow for the given [sku].
*/
override fun purchase(activity: Activity, sku: BillingProvider.SkuDetails): Boolean {
val params = BillingFlowParams.newBuilder()
.setSkuDetails(SkuDetails(sku.originalJSON))
.build()
val result = client.launchBillingFlow(activity, params)
if (result.responseCode != BillingClient.BillingResponseCode.OK) {
Log.w(LOG_TAG, "failed to start billing flow: ${result.debugMessage}")
return false
}
return true
}
override fun consumePurchase(orderId: String) {
defaultScope.launch(Dispatchers.IO) {
prefsMutex.withLock {
val orders = prefs.getMutableStringSet(PREF_UNCONSUMED_ORDERS)
orders.add(orderId)
prefs.edit(commit = true) { putStringSet(PREF_UNCONSUMED_ORDERS, orders) }
Log.d(LOG_TAG, "consumePurchase: add to unconsumed orders")
}
refreshPurchases()
}
}
private fun refreshPurchases() {
defaultScope.launch(Dispatchers.IO) {
waitForBillingClientConnection()
if (!client.isReady) {
Log.d(LOG_TAG, "refreshPurchases: client is not ready")
} else {
reconcilePurchases()
}
}
}
@VisibleForTesting
internal suspend fun reconcilePurchases(verifyPurchases: Boolean = true) = prefsMutex.withLock {
val purchases: List<Purchase>
try {
purchases = queryPurchases()
} catch (e: QueryPurchasesException) {
Log.w(LOG_TAG, "reconcilePurchases: query purchase failed", e)
return
}
val pendingOrders = prefs.getMutableStringSet(PREF_PENDING_ORDERS)
val unconsumedOrders = prefs.getMutableStringSet(PREF_UNCONSUMED_ORDERS)
for (p in purchases) {
if (verifyPurchases && !isVerifiedPurchase(p)) {
continue
}
if (p.purchaseState == Purchase.PurchaseState.PENDING && pendingOrders.add(p.orderId)) {
Log.d(LOG_TAG, "reconcilePurchases: new pending order skus=${p.skus}")
defaultScope.launch(Dispatchers.Main) { purchaseListener?.onPending(p.skus) }
}
if (p.purchaseState == Purchase.PurchaseState.PURCHASED && !p.isAcknowledged) {
pendingOrders.remove(p.orderId)
Log.d(LOG_TAG, "reconcilePurchases: new purchased order skus=${p.skus}")
try {
acknowledgePurchase(p.purchaseToken)
Log.d(LOG_TAG, "reconcilePurchases: acknowledged skus=${p.skus}")
defaultScope.launch(Dispatchers.Main) {
purchaseListener?.onComplete(p.skus, p.orderId)
}
} catch (e: AcknowledgePurchaseException) {
Log.w(LOG_TAG, "reconcilePurchases: acknowledge purchase failed", e)
}
}
// consume marked purchases.
if (p.purchaseState == Purchase.PurchaseState.PURCHASED && p.orderId in unconsumedOrders) {
try {
consumePurchaseAsync(p.purchaseToken)
unconsumedOrders.remove(p.orderId)
Log.d(LOG_TAG, "reconcilePurchases: consumed skus=${p.skus}")
} catch (e: ConsumePurchaseException) {
Log.w(LOG_TAG, "reconcilePurchases: consume purchase failed", e)
}
}
}
prefs.edit(commit = true) {
putStringSet(PREF_PENDING_ORDERS, pendingOrders)
putStringSet(PREF_UNCONSUMED_ORDERS, unconsumedOrders)
}
}
private suspend fun waitForBillingClientConnection() {
while (isConnecting.get()) {
delay(500)
}
}
/**
* Query all purchases.
*
* @return list of in-app and subscription purchases
* @throws QueryPurchasesException when the query fails.
*/
@Throws(QueryPurchasesException::class)
private suspend fun queryPurchases(): List<Purchase> {
return queryPurchases(BillingClient.SkuType.SUBS) + queryPurchases(BillingClient.SkuType.INAPP)
}
/**
* Query purchases of the provided [BillingClient.SkuType] [type].
*
* @return list of purchases
* @throws QueryPurchasesException when the query fails.
*/
@Throws(QueryPurchasesException::class)
private suspend fun queryPurchases(@BillingClient.SkuType type: String): List<Purchase> {
return suspendCancellableCoroutine { c ->
client.queryPurchasesAsync(type) { result, purchaseList ->
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
c.resume(purchaseList) { e ->
Log.d(LOG_TAG, "queryPurchases cancelled", e)
}
} else {
c.resumeWithException(QueryPurchasesException(result.debugMessage))
}
}
}
}
private fun isVerifiedPurchase(p: Purchase): Boolean {
if (p.signature.isBlank() || p.originalJson.isBlank()) {
return false
}
try {
val signatureBytes = Base64.decode(p.signature, Base64.DEFAULT)
val signatureAlgorithm = Signature.getInstance("SHA1withRSA")
signatureAlgorithm.initVerify(securityKey)
signatureAlgorithm.update(p.originalJson.toByteArray())
if (signatureAlgorithm.verify(signatureBytes)) {
return true
}
Log.w(LOG_TAG, "Signature verification failed")
} catch (e: IllegalArgumentException) {
Log.w(LOG_TAG, "Base64 decoding failed", e)
} catch (e: SignatureException) {
Log.e(LOG_TAG, "Signature exception", e)
}
return false
}
/**
* Acknowledge a new purchase.
*
* @throws AcknowledgePurchaseException when the acknowledge query fails.
*/
@Throws(AcknowledgePurchaseException::class)
private suspend fun acknowledgePurchase(token: String) {
return suspendCancellableCoroutine { c ->
val params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(token)
.build()
client.acknowledgePurchase(params) { result ->
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
c.resume(Unit) { e ->
Log.d(LOG_TAG, "acknowledgePurchase cancelled", e)
}
} else {
c.resumeWithException(AcknowledgePurchaseException(result.debugMessage))
}
}
}
}
/**
* Consume an in-app purchase.
*
* @throws ConsumePurchaseException when the consume query fails.
*/
@Throws(ConsumePurchaseException::class)
private suspend fun consumePurchaseAsync(token: String) {
val r = client.consumePurchase(
ConsumeParams.newBuilder()
.setPurchaseToken(token)
.build()
)
if (r.billingResult.responseCode != BillingClient.BillingResponseCode.OK) {
throw ConsumePurchaseException(r.billingResult.debugMessage)
}
}
class QueryPurchasesException(msg: String) : Exception(msg)
class AcknowledgePurchaseException(msg: String) : Exception(msg)
class ConsumePurchaseException(msg: String) : Exception(msg)
}

View File

@ -0,0 +1,166 @@
package com.github.ashutoshgngwr.noice.provider
import android.content.Context
import android.view.Menu
import android.view.MenuItem
import androidx.annotation.StringRes
import androidx.annotation.VisibleForTesting
import androidx.core.view.MenuItemCompat
import androidx.media.VolumeProviderCompat
import androidx.mediarouter.app.MediaRouteActionProvider
import com.github.ashutoshgngwr.noice.BuildConfig
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.playback.strategy.CastPlaybackStrategyFactory
import com.github.ashutoshgngwr.noice.playback.strategy.PlaybackStrategyFactory
import com.google.android.gms.cast.framework.CastButtonFactory
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastOptions
import com.google.android.gms.cast.framework.CastSession
import com.google.android.gms.cast.framework.OptionsProvider
import com.google.android.gms.cast.framework.SessionManagerListener
import com.google.android.gms.cast.framework.SessionProvider
import com.google.android.gms.cast.framework.media.CastMediaOptions
import kotlin.math.round
/**
* [RealCastAPIProvider] wraps all the Google Cast API functionality used by the application
* for the full build variant.
*/
class RealCastAPIProvider(context: Context) : CastAPIProvider {
private val sessionListeners = mutableSetOf<CastAPIProvider.SessionListener>()
private val castContext = CastContext.getSharedInstance(context)
private val castSessionManagerListener = object : SessionManagerListener<CastSession> {
override fun onSessionStarted(session: CastSession, sessionId: String) {
sessionListeners.forEach { it.onSessionBegin() }
}
override fun onSessionResumed(session: CastSession, wasSuspended: Boolean) {
sessionListeners.forEach { it.onSessionBegin() }
}
override fun onSessionEnded(session: CastSession, error: Int) {
sessionListeners.forEach { it.onSessionEnd() }
}
override fun onSessionResumeFailed(session: CastSession, error: Int) = Unit
override fun onSessionSuspended(session: CastSession, reason: Int) = Unit
override fun onSessionStarting(session: CastSession) = Unit
override fun onSessionResuming(session: CastSession, sessionId: String) = Unit
override fun onSessionEnding(session: CastSession) = Unit
override fun onSessionStartFailed(session: CastSession, error: Int) = Unit
}
/**
* Sets up the cast media menu item on the given menu with given title resource.
*/
override fun addMenuItem(context: Context, menu: Menu, @StringRes titleResId: Int) {
menu.add(titleResId).also {
it.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
MenuItemCompat.setActionProvider(it, MediaRouteActionProvider(context))
CastButtonFactory.setUpMediaRouteButton(context, menu, it.itemId)
}
}
/**
* Initializes a new [CastPlaybackStrategyFactory] instance and returns it as
* [PlaybackStrategyFactory].
*/
override fun getPlaybackStrategyFactory(context: Context): PlaybackStrategyFactory =
CastPlaybackStrategyFactory(
context,
requireNotNull(castContext.sessionManager.currentCastSession),
context.getString(R.string.cast_namespace__default)
)
/**
* Creates a new [VolumeProviderCompat] instance that can be used with
* [android.support.v4.media.session.MediaSessionCompat.setPlaybackToRemote].
*/
override fun getVolumeProvider(): VolumeProviderCompat =
CastVolumeProvider(requireNotNull(castContext.sessionManager.currentCastSession))
override fun registerSessionListener(listener: CastAPIProvider.SessionListener) {
// add `castSessionManagerListener` only when the first `CastAPIProvider.SessionListener` is
// registered.
if (sessionListeners.isEmpty()) {
castContext.sessionManager.addSessionManagerListener(
castSessionManagerListener,
CastSession::class.java
)
}
sessionListeners.add(listener)
}
override fun unregisterSessionListener(listener: CastAPIProvider.SessionListener) {
sessionListeners.remove(listener)
// remove `castSessionManagerListener` when the last `CastAPIProvider.SessionListener` is
// unregistered.
if (sessionListeners.isEmpty()) {
castContext.sessionManager.removeSessionManagerListener(
castSessionManagerListener,
CastSession::class.java
)
}
}
}
@Suppress("unused") // Referred from 'AndroidManifest.xml'
class CastOptionsProvider : OptionsProvider {
override fun getCastOptions(context: Context): CastOptions {
return CastOptions.Builder().run {
setReceiverApplicationId(
context.getString(
@Suppress("ConstantConditionIf")
if (BuildConfig.DEBUG) {
R.string.cast_app_id__debug
} else {
R.string.cast_app_id__release
}
)
)
setStopReceiverApplicationWhenEndingSession(true)
setCastMediaOptions(
CastMediaOptions.Builder()
.setMediaSessionEnabled(false)
.build()
)
build()
}
}
override fun getAdditionalSessionProviders(context: Context?): List<SessionProvider>? = null
}
/**
* A [VolumeProviderCompat] implementation for adjusting cast device volume using active
* [MediaSession][android.support.v4.media.session.MediaSessionCompat]'s remote playback
* control.
*/
internal class CastVolumeProvider(private val session: CastSession) :
VolumeProviderCompat(VOLUME_CONTROL_ABSOLUTE, MAX_VOLUME, multiply(session.volume)) {
companion object {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val MAX_VOLUME = 15
private fun multiply(volume: Double): Int {
return round(volume * MAX_VOLUME).toInt()
}
}
override fun onSetVolumeTo(volume: Int) {
session.volume = volume.toDouble() / MAX_VOLUME
this.currentVolume = volume
}
override fun onAdjustVolume(direction: Int) {
onSetVolumeTo(this.currentVolume + direction)
}
}

View File

@ -0,0 +1,24 @@
package com.github.ashutoshgngwr.noice.provider
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
/**
* [RealCrashlyticsProvider] provides a real concrete implementation of Crashlytics API.
*/
object RealCrashlyticsProvider : CrashlyticsProvider {
private val fc = Firebase.crashlytics
override fun recordException(e: Throwable) {
fc.recordException(e)
}
override fun setCollectionEnabled(e: Boolean) {
fc.setCrashlyticsCollectionEnabled(e)
}
override fun log(m: String) {
fc.log(m)
}
}

View File

@ -0,0 +1,121 @@
package com.github.ashutoshgngwr.noice.widget
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.util.AttributeSet
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.appcompat.widget.LinearLayoutCompat
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.databinding.DonateViewBinding
import com.github.ashutoshgngwr.noice.provider.BillingProvider
import com.google.android.material.button.MaterialButton
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
class InAppBillingDonateView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayoutCompat(context, attrs, defStyleAttr) {
private lateinit var defaultScope: CoroutineScope
private val billingProvider = NoiceApplication.of(context).billingProvider
private val binding: DonateViewBinding =
DonateViewBinding.inflate(LayoutInflater.from(context), this)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal constructor(context: Context, defaultScope: CoroutineScope) : this(context) {
this.defaultScope = defaultScope
}
init {
orientation = VERTICAL
gravity = Gravity.CENTER
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
binding.progressCircle.visibility = View.VISIBLE
binding.error.visibility = View.GONE
binding.buttonContainer.visibility = View.GONE
defaultScope = CoroutineScope(Job() + CoroutineName("DonateViewScope"))
defaultScope.launch(Dispatchers.IO) { loadSkuDetails() }
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal suspend fun loadSkuDetails() {
try {
val detailsList = billingProvider.queryDetails(
BillingProvider.SkuType.INAPP, listOf(
"donate_usd1", "donate_usd2", "donate_usd5",
"donate_usd10", "donate_usd15", "donate_usd25",
)
)
defaultScope.launch(Dispatchers.Main) {
setDetails(detailsList.sortedBy { it.priceAmountMicros })
}
} catch (e: BillingProvider.QueryDetailsException) {
Log.w(this::class.simpleName, "failed to load sku details", e)
defaultScope.launch(Dispatchers.Main) { setQueryDetailsFailedError() }
}
}
private fun setDetails(detailsList: List<BillingProvider.SkuDetails>) {
binding.progressCircle.visibility = View.GONE
binding.error.visibility = View.GONE
binding.buttonContainer.visibility = View.VISIBLE
binding.buttonContainer.removeAllViews()
detailsList.forEach { details ->
val b = MaterialButton(context, null, R.attr.materialButtonOutlinedStyle)
b.text = details.price
b.setOnClickListener {
if (!billingProvider.purchase(getActivity(), details)) {
Snackbar.make(this, R.string.failed_to_purchase, Snackbar.LENGTH_LONG).show()
}
}
binding.buttonContainer.addView(b)
}
}
private fun setQueryDetailsFailedError() {
binding.progressCircle.visibility = View.GONE
binding.buttonContainer.visibility = View.GONE
binding.error.visibility = View.VISIBLE
binding.error.setText(R.string.failed_to_load_inapp_purchases)
}
// https://android.googlesource.com/platform/frameworks/support/+/refs/heads/marshmallow-release/v7/mediarouter/src/android/support/v7/app/MediaRouteButton.java#262
private fun getActivity(): Activity {
// Gross way of unwrapping the Activity
var context = context
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
throw IllegalStateException("unable to find activity that owns this donate view")
}
override fun onDetachedFromWindow() {
defaultScope.cancel()
super.onDetachedFromWindow()
}
}

View File

@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M11 15h2v2h-2zm0-8h2v6h-2zm0.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" />
</vector>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.github.ashutoshgngwr.noice.widget.MarkdownTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginVertical="10dp"
android:lineSpacingMultiplier="1.25"
android:text="@string/support_development__donate_google_play_description"
android:textAppearance="?attr/textAppearanceBody1" />
<ProgressBar
android:id="@+id/progress_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:indeterminate="true" />
<TextView
android:id="@+id/error"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:drawablePadding="10dp"
android:textColor="@color/error"
app:drawableStartCompat="@drawable/ic_error_24dp"
app:drawableTint="@color/error" />
<com.google.android.flexbox.FlexboxLayout
android:id="@+id/button_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:alignContent="stretch"
app:alignItems="stretch"
app:flexWrap="wrap"
app:justifyContent="space_evenly" />
</merge>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<string name="cast_app_id__debug" tools:ignore="UnusedResources">EB68E994</string>
<string name="cast_app_id__release" tools:ignore="UnusedResources">E421E43B</string>
<string name="cast_namespace__default">urn:x-cast:com.github.ashutoshgngwr.noice</string>
</resources>

View File

@ -0,0 +1,99 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.github.ashutoshgngwr.noice">
<uses-feature
android:name="android.hardware.audio.output"
android:required="true" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<application
android:name="com.github.ashutoshgngwr.noice.NoiceApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.App"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity
android:name=".activity.MainActivity"
android:exported="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.APPLICATION_PREFERENCES" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="ashutoshgngwr.github.io"
android:pathPrefix="/noice/preset"
android:scheme="https" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="preset"
android:scheme="noice" />
</intent-filter>
</activity>
<activity
android:name=".activity.AppIntroActivity"
android:theme="@style/Theme.MaterialComponents.NoActionBar" />
<activity
android:name=".activity.ShortcutHandlerActivity"
android:excludeFromRecents="true"
android:exported="true" />
<activity
android:name=".activity.AlarmRingerActivity"
android:excludeFromRecents="true"
android:launchMode="singleInstance" />
<service android:name=".MediaPlayerService" />
<receiver
android:name=".WakeUpTimerManager$BootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,148 @@
package com.github.ashutoshgngwr.noice
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import androidx.core.content.getSystemService
import androidx.mediarouter.media.MediaRouter
import com.github.ashutoshgngwr.noice.activity.MainActivity
import com.github.ashutoshgngwr.noice.model.Preset
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.playback.Player
import com.github.ashutoshgngwr.noice.playback.PlayerManager
import com.github.ashutoshgngwr.noice.playback.PlayerNotificationManager
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit
class MediaPlayerService : Service() {
/**
* [MediaPlayerService] publishes [PlaybackUpdateEvent] whenever there's an update to
* [PlayerManager].
*
* @param state [PlaybackStateCompat] representing the current player state
* @param players a snapshot of currently playing sound [Players][Player]
*/
data class PlaybackUpdateEvent(val state: Int, val players: Map<String, Player>)
companion object {
private val TAG = MediaPlayerService::class.java.simpleName
private val WAKELOCK_TIMEOUT = TimeUnit.DAYS.toMillis(1)
private const val FOREGROUND_ID = 0x29
private const val RC_MAIN_ACTIVITY = 0x28
}
private lateinit var wakeLock: PowerManager.WakeLock
private lateinit var mediaSession: MediaSessionCompat
private lateinit var playerManager: PlayerManager
private lateinit var presetRepository: PresetRepository
private lateinit var settingsRepository: SettingsRepository
private val becomingNoisyReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
Log.i(TAG, "Becoming noisy... Pause playback!")
playerManager.pause()
}
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
wakeLock = requireNotNull(getSystemService<PowerManager>()).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, packageName).apply {
setReferenceCounted(false)
}
}
mediaSession = MediaSessionCompat(this, "$TAG.mediaSession").also {
var piFlags = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
piFlags = piFlags or PendingIntent.FLAG_IMMUTABLE
}
it.setSessionActivity(
PendingIntent.getActivity(
this, RC_MAIN_ACTIVITY, Intent(this, MainActivity::class.java), piFlags
)
)
it.setPlaybackToLocal(AudioManager.STREAM_MUSIC)
it.isActive = true
MediaRouter.getInstance(this).setMediaSessionCompat(it)
}
playerManager = PlayerManager(this, mediaSession)
playerManager.setPlaybackUpdateListener(this::onPlaybackUpdate)
presetRepository = PresetRepository.newInstance(this)
settingsRepository = SettingsRepository.newInstance(this)
PlayerNotificationManager.createChannel(this)
registerReceiver(becomingNoisyReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY))
}
private fun onPlaybackUpdate(state: Int, players: Map<String, Player>) {
EventBus.getDefault().postSticky(PlaybackUpdateEvent(state, players))
val currentPreset = getCurrentPreset(players.values)
val title = currentPreset?.name ?: getString(R.string.unsaved_preset)
mediaSession.setMetadata(
MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
.build()
)
if (state == PlaybackStateCompat.STATE_STOPPED) {
stopForeground(true)
wakeLock.release()
} else {
wakeLock.acquire(WAKELOCK_TIMEOUT)
startForeground(
FOREGROUND_ID,
PlayerNotificationManager.createNotification(
this, mediaSession, title,
currentPreset != null
)
)
}
}
private fun getCurrentPreset(players: Collection<Player>): Preset? {
if (players.isEmpty()) {
return null
}
return Preset.from("", players).let {
presetRepository.list().find { p -> p == it }
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
intent?.also { PlaybackController.handleServiceIntent(this, playerManager, it) }
return START_STICKY
}
override fun onDestroy() {
unregisterReceiver(becomingNoisyReceiver)
playerManager.cleanup()
mediaSession.release()
PlaybackController.clearAutoStopCallback()
wakeLock.release()
super.onDestroy()
}
}

View File

@ -0,0 +1,85 @@
package com.github.ashutoshgngwr.noice
import android.content.Context
import androidx.annotation.CallSuper
import androidx.annotation.VisibleForTesting
import com.github.ashutoshgngwr.noice.provider.AnalyticsProvider
import com.github.ashutoshgngwr.noice.provider.BillingProvider
import com.github.ashutoshgngwr.noice.provider.CastAPIProvider
import com.github.ashutoshgngwr.noice.provider.CrashlyticsProvider
import com.github.ashutoshgngwr.noice.provider.DonateViewProvider
import com.github.ashutoshgngwr.noice.provider.DummyAnalyticsProvider
import com.github.ashutoshgngwr.noice.provider.DummyBillingProvider
import com.github.ashutoshgngwr.noice.provider.DummyCastAPIProvider
import com.github.ashutoshgngwr.noice.provider.DummyCrashlyticsProvider
import com.github.ashutoshgngwr.noice.provider.GitHubReviewFlowProvider
import com.github.ashutoshgngwr.noice.provider.OpenCollectiveDonateViewProvider
import com.github.ashutoshgngwr.noice.provider.ReviewFlowProvider
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
open class NoiceApplication : android.app.Application() {
companion object {
/**
* Convenience method that returns [NoiceApplication] from the provided [context].
*/
fun of(context: Context): NoiceApplication = context.applicationContext as NoiceApplication
}
lateinit var castAPIProvider: CastAPIProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
lateinit var reviewFlowProvider: ReviewFlowProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
lateinit var crashlyticsProvider: CrashlyticsProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
lateinit var analyticsProvider: AnalyticsProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
lateinit var billingProvider: BillingProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
lateinit var donateViewProvider: DonateViewProvider
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal set
override fun onCreate() {
super.onCreate()
initProviders()
SettingsRepository.newInstance(this)
.shouldShareUsageData()
.also {
analyticsProvider.setCollectionEnabled(it)
crashlyticsProvider.setCollectionEnabled(it)
}
}
/**
* [initProviders] is invoked when application is created (in [onCreate]). It can be overridden by
* a subclass to swap default implementations of [castAPIProvider], [reviewFlowProvider],
* [crashlyticsProvider], [analyticsProvider], [billingProvider] and [donateViewProvider].
*/
@CallSuper
protected open fun initProviders() {
castAPIProvider = DummyCastAPIProvider
reviewFlowProvider = GitHubReviewFlowProvider
crashlyticsProvider = DummyCrashlyticsProvider
analyticsProvider = DummyAnalyticsProvider
billingProvider = DummyBillingProvider
donateViewProvider = OpenCollectiveDonateViewProvider
}
/**
* Indicates if Google Mobile Services are available on the client device.
*/
open fun isGoogleMobileServicesAvailable(): Boolean {
return false
}
}

View File

@ -0,0 +1,139 @@
package com.github.ashutoshgngwr.noice
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import androidx.core.content.getSystemService
import androidx.preference.PreferenceManager
import com.github.ashutoshgngwr.noice.activity.AlarmRingerActivity
import com.github.ashutoshgngwr.noice.activity.MainActivity
import com.github.ashutoshgngwr.noice.repository.PresetRepository
import com.google.gson.GsonBuilder
import com.google.gson.annotations.Expose
object WakeUpTimerManager {
/**
* [Timer] declares fields necessary to schedule a Wake-up timer.
*/
data class Timer(@Expose var presetID: String, @Expose var atMillis: Long)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val PREF_WAKE_UP_TIMER = "wake_up_timer"
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val PREF_LAST_USED_PRESET_ID = "last_used_preset_id"
private const val RC_MAIN_ACTIVITY = 0x40
private val gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
private inline fun <T> withAlarmManager(ctx: Context, crossinline block: (AlarmManager) -> T): T {
return with(requireNotNull(ctx.getSystemService()), block)
}
private fun getPendingIntentForActivity(context: Context) =
Intent(context, MainActivity::class.java).let {
it.putExtra(MainActivity.EXTRA_NAV_DESTINATION, R.id.wake_up_timer)
var piFlags = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
piFlags = piFlags or PendingIntent.FLAG_IMMUTABLE
}
PendingIntent.getActivity(context, RC_MAIN_ACTIVITY, it, piFlags)
}
/**
* [set] schedules the given [Timer] using Android's [AlarmManager]. It also persists the [Timer]
* instance onto device storage to be able return it later upon querying.
*/
fun set(context: Context, timer: Timer) {
if (timer.atMillis < System.currentTimeMillis()) {
return
}
if (PresetRepository.newInstance(context).get(timer.presetID) == null) {
return
}
PreferenceManager.getDefaultSharedPreferences(context).edit {
putString(PREF_WAKE_UP_TIMER, gson.toJson(timer))
}
withAlarmManager(context) {
it.setAlarmClock(
AlarmManager.AlarmClockInfo(timer.atMillis, getPendingIntentForActivity(context)),
AlarmRingerActivity.getPendingIntent(context, timer.presetID)
)
}
}
/**
* [cancel] cancels the last scheduled timer.
*/
fun cancel(context: Context) {
PreferenceManager.getDefaultSharedPreferences(context).edit {
remove(PREF_WAKE_UP_TIMER)
}
withAlarmManager(context) {
// don't need concrete timer value for cancelling the alarm.
it.cancel(AlarmRingerActivity.getPendingIntent(context, null))
}
}
/**
* [get] returns the last scheduled timer if found in the persisted state. Returns null otherwise.
*/
fun get(context: Context): Timer? {
val timer = PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_WAKE_UP_TIMER, null)
return gson.fromJson(timer, Timer::class.java)
}
/**
* [saveLastUsedPresetID] saves the ID of the preset last used by the user in a Wake-up timer.
*/
fun saveLastUsedPresetID(context: Context, selectedPresetID: String?) {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
with(sharedPrefs.edit()) {
putString(PREF_LAST_USED_PRESET_ID, selectedPresetID)
apply()
}
}
/**
* [getLastUsedPresetID] return the saved ID of the last selected preset. Returns null otherwise.
*/
fun getLastUsedPresetID(context: Context): String? {
return with(PreferenceManager.getDefaultSharedPreferences(context)) {
val lastSelectedPresetID = getString(PREF_LAST_USED_PRESET_ID, null)
// ensure that preset with given ID exists in preferences.
PresetRepository.newInstance(context).get(lastSelectedPresetID)?.id
}
}
/**
* [BootReceiver] ensures that a scheduled [Timer] is able to persist across device restarts.
*/
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (Intent.ACTION_BOOT_COMPLETED != intent?.action) {
return
}
val timer = get(context) ?: return
if (timer.atMillis > System.currentTimeMillis()) {
set(context, timer)
}
}
}
}

View File

@ -0,0 +1,153 @@
package com.github.ashutoshgngwr.noice.activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Window
import android.view.WindowManager
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.media.AudioAttributesCompat
import com.github.ashutoshgngwr.noice.MediaPlayerService
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.databinding.AlarmRingerActivityBinding
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.playback.strategy.LocalPlaybackStrategy
import com.github.ashutoshgngwr.noice.provider.AnalyticsProvider
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import com.ncorti.slidetoact.SlideToActView
class AlarmRingerActivity : AppCompatActivity(), SlideToActView.OnSlideCompleteListener {
companion object {
@VisibleForTesting
internal const val EXTRA_PRESET_ID = "preset_id"
private const val RC_ALARM = 0x39
private val LOG_TAG = AlarmRingerActivity::class.simpleName
fun getPendingIntent(context: Context, presetID: String?): PendingIntent {
var piFlags = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
piFlags = piFlags or PendingIntent.FLAG_IMMUTABLE
}
return Intent(context, AlarmRingerActivity::class.java)
.putExtra(EXTRA_PRESET_ID, presetID)
.let { PendingIntent.getActivity(context, RC_ALARM, it, piFlags) }
}
}
private lateinit var binding: AlarmRingerActivityBinding
private lateinit var settingsRepository: SettingsRepository
private lateinit var analyticsProvider: AnalyticsProvider
private var ringerStartTime: Long = 0L
override fun onCreate(savedInstanceState: Bundle?) {
settingsRepository = SettingsRepository.newInstance(this)
AppCompatDelegate.setDefaultNightMode(settingsRepository.getAppThemeAsNightMode())
super.onCreate(savedInstanceState)
supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
binding = AlarmRingerActivityBinding.inflate(layoutInflater)
binding.dismissSlider.onSlideCompleteListener = this
setContentView(binding.root)
showWhenLocked()
analyticsProvider = NoiceApplication.of(this).analyticsProvider
ringerStartTime = System.currentTimeMillis()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
setIntent(intent)
}
override fun onResume() {
super.onResume()
enableImmersiveMode()
// handle the new intent here since onResume() is guaranteed to be called after onNewIntent().
// https://developer.android.com/reference/android/app/Activity#onNewIntent(android.content.Intent)
val presetID = intent.getStringExtra(EXTRA_PRESET_ID)
if (presetID == null) {
Log.d(LOG_TAG, "onResume(): presetID is null")
finish()
return
}
// Since activity takes a moment to actually show up, invoking `startService` from `onCreate` or
// `onResume` fails with `java.lang.IllegalStateException: Not allowed to start service Intent:
// app is in background` on recent Android version (O+). `PlaybackController` can not call
// `startForegroundService` since it doesn't know if an action will bring `MediaPlayerService`
// to foreground. To prevent `PlaybackController` from causing this error by invoking
// `startService`, we need to manually start `MediaPlayerService` in the foreground since we can
// be certain that playPreset action will bring it to foreground before Android System kills it.
ContextCompat.startForegroundService(this, Intent(this, MediaPlayerService::class.java))
Log.d(LOG_TAG, "onResume(): starting preset")
PlaybackController.setAudioUsage(this, AudioAttributesCompat.USAGE_ALARM)
PlaybackController.playPreset(this, presetID)
}
override fun onStop() {
super.onStop()
if (!isFinishing) {
return
}
Log.d(LOG_TAG, "onStop(): pausing playback")
PlaybackController.pause(this)
// TODO: find a better solution to wait for pause transition to finish before switching streams.
Handler(mainLooper).postDelayed({
PlaybackController.setAudioUsage(this, AudioAttributesCompat.USAGE_MEDIA)
}, LocalPlaybackStrategy.DEFAULT_FADE_DURATION)
val duration = System.currentTimeMillis() - ringerStartTime
analyticsProvider.logEvent("alarm_ringer_session", bundleOf("duration_ms" to duration))
}
override fun onBackPressed() = Unit
override fun onSlideComplete(view: SlideToActView) {
finish()
}
private fun enableImmersiveMode() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
window.attributes.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
}
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowCompat.getInsetsController(window, binding.root)?.apply {
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
hide(WindowInsetsCompat.Type.systemBars())
}
}
private fun showWhenLocked() {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
@Suppress("Deprecation")
window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
}
}

View File

@ -0,0 +1,133 @@
package com.github.ashutoshgngwr.noice.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.VisibleForTesting
import androidx.core.app.ActivityCompat
import androidx.core.content.edit
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.preference.PreferenceManager
import com.github.appintro.AppIntro
import com.github.appintro.AppIntroPageTransformerType
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.fragment.AppIntroFragment
import com.github.ashutoshgngwr.noice.provider.AnalyticsProvider
class AppIntroActivity : AppIntro() {
companion object {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
const val PREF_HAS_USER_SEEN_APP_INTRO = "has_user_seen_app_intro"
/**
* [maybeStart] displays the [AppIntroActivity] if user hasn't seen it before.
*/
fun maybeStart(context: Context) {
PreferenceManager.getDefaultSharedPreferences(context).also {
if (!it.getBoolean(PREF_HAS_USER_SEEN_APP_INTRO, false)) {
context.startActivity(Intent(context, AppIntroActivity::class.java))
}
}
}
}
private lateinit var analyticsProvider: AnalyticsProvider
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
isColorTransitionsEnabled = true
showStatusBar(true)
setStatusBarColor(ActivityCompat.getColor(this, R.color.status_bar))
setTransformer(
AppIntroPageTransformerType.Parallax(
titleParallaxFactor = 1.0,
imageParallaxFactor = -1.0,
descriptionParallaxFactor = 2.0
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__getting_started_title),
description = "${getString(R.string.app_description)}\n\n${getString(R.string.appintro__getting_started_desc_0)}",
imageDrawable = R.drawable.app_banner,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_0__background)
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__library_title),
description = getString(R.string.appintro__library_desc),
imageDrawable = R.drawable.ic_appintro_library,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_1__background)
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__presets_title),
description = getString(R.string.appintro__presets_desc),
imageDrawable = R.drawable.ic_appintro_presets,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_2__background)
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__timer_title),
description = getString(R.string.appintro__timer_desc),
imageDrawable = R.drawable.ic_appintro_sleep_timer,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_3__background)
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__chromecast_title),
description = getString(R.string.appintro__chromecast_desc),
imageDrawable = R.drawable.ic_appintro_chromecast,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_4__background)
)
)
addSlide(
AppIntroFragment.newInstance(
title = getString(R.string.appintro__getting_started_title),
description = getString(R.string.appintro__getting_started_desc_1),
imageDrawable = R.drawable.app_banner,
titleColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
descriptionColor = ActivityCompat.getColor(this, R.color.appintro__text_color),
backgroundColor = ActivityCompat.getColor(this, R.color.appintro_slide_5__background)
)
)
analyticsProvider = NoiceApplication.of(this).analyticsProvider
analyticsProvider.setCurrentScreen("app_intro", AppIntroActivity::class)
}
override fun onSkipPressed(currentFragment: Fragment?) {
markSeenInPrefsAndFinish(true)
}
override fun onDonePressed(currentFragment: Fragment?) {
markSeenInPrefsAndFinish(false)
}
private fun markSeenInPrefsAndFinish(isSkipped: Boolean) {
PreferenceManager.getDefaultSharedPreferences(this).edit {
putBoolean(PREF_HAS_USER_SEEN_APP_INTRO, true)
}
finish()
analyticsProvider.logEvent("app_intro_complete", bundleOf("success" to !isSkipped))
}
}

View File

@ -0,0 +1,180 @@
package com.github.ashutoshgngwr.noice.activity
import android.content.Intent
import android.os.Bundle
import androidx.annotation.VisibleForTesting
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.core.os.bundleOf
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.preference.PreferenceManager
import com.github.ashutoshgngwr.noice.BuildConfig
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.databinding.MainActivityBinding
import com.github.ashutoshgngwr.noice.fragment.DialogFragment
import com.github.ashutoshgngwr.noice.navigation.Navigable
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.provider.BillingProvider
import com.github.ashutoshgngwr.noice.repository.SettingsRepository
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity(), BillingProvider.PurchaseListener {
companion object {
/**
* [EXTRA_NAV_DESTINATION] declares the key for intent extra value passed to [MainActivity] for
* setting the current destination on the [NavController]. The value for this extra should be an
* id resource representing the action/destination id present in the [main][R.navigation.main]
* or [home][R.navigation.home] navigation graphs.
*/
internal const val EXTRA_NAV_DESTINATION = "nav_destination"
@VisibleForTesting
internal const val PREF_HAS_SEEN_DATA_COLLECTION_CONSENT = "has_seen_data_collection_consent"
@VisibleForTesting
internal const val PREF_HAS_SEEN_V2_ANNOUNCEMENT = "has_seen_v2_announcement"
}
private lateinit var binding: MainActivityBinding
private lateinit var settingsRepository: SettingsRepository
private lateinit var app: NoiceApplication
private lateinit var navController: NavController
/**
* indicates whether the activity was delivered a new intent since it was last resumed.
*/
private var hasNewIntent = false
override fun onCreate(savedInstanceState: Bundle?) {
app = NoiceApplication.of(this)
settingsRepository = SettingsRepository.newInstance(this)
AppCompatDelegate.setDefaultNightMode(settingsRepository.getAppThemeAsNightMode())
super.onCreate(savedInstanceState)
binding = MainActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment = requireNotNull(binding.navHostFragment.getFragment<NavHostFragment>())
navController = navHostFragment.navController
setupActionBarWithNavController(navController, AppBarConfiguration(navController.graph))
AppIntroActivity.maybeStart(this)
maybeShowV2Announcement()
if (!BuildConfig.IS_FREE_BUILD) {
maybeShowDataCollectionConsent()
}
app.reviewFlowProvider.init(this)
app.billingProvider.init(this, this)
app.analyticsProvider.logEvent("ui_open", bundleOf("theme" to settingsRepository.getAppTheme()))
hasNewIntent = true
}
private fun maybeShowV2Announcement() {
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
if (prefs.getBoolean(PREF_HAS_SEEN_V2_ANNOUNCEMENT, false)) {
return
}
DialogFragment.show(supportFragmentManager) {
title(R.string.v2_announcement_title)
message(R.string.v2_announcement_message)
positiveButton(R.string.okay)
onDismiss {
prefs.edit { putBoolean(PREF_HAS_SEEN_V2_ANNOUNCEMENT, true) }
}
}
}
private fun maybeShowDataCollectionConsent() {
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
if (prefs.getBoolean(PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, false)) {
return
}
DialogFragment.show(supportFragmentManager) {
isCancelable = false
title(R.string.share_usage_data_consent_title)
message(R.string.share_usage_data_consent_message)
positiveButton(R.string.accept) {
settingsRepository.setShouldShareUsageData(true)
app.analyticsProvider.setCollectionEnabled(true)
app.crashlyticsProvider.setCollectionEnabled(true)
prefs.edit { putBoolean(PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, true) }
}
negativeButton(R.string.decline) {
settingsRepository.setShouldShareUsageData(false)
app.analyticsProvider.setCollectionEnabled(false)
app.crashlyticsProvider.setCollectionEnabled(false)
prefs.edit { putBoolean(PREF_HAS_SEEN_DATA_COLLECTION_CONSENT, true) }
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
navController.handleDeepLink(intent)
hasNewIntent = true
}
override fun onResume() {
super.onResume()
// handle the new intent here since onResume() is guaranteed to be called after onNewIntent().
// https://developer.android.com/reference/android/app/Activity#onNewIntent(android.content.Intent)
if (!hasNewIntent) {
return
}
hasNewIntent = false
if (intent.hasExtra(EXTRA_NAV_DESTINATION)) {
val destID = intent.getIntExtra(EXTRA_NAV_DESTINATION, 0)
if (!Navigable.navigate(binding.navHostFragment.getFragment(), destID)) {
navController.navigate(destID)
}
} else if (Intent.ACTION_APPLICATION_PREFERENCES == intent.action) {
navController.navigate(R.id.settings)
}
if (Intent.ACTION_VIEW == intent.action &&
(intent.dataString?.startsWith("https://ashutoshgngwr.github.io/noice/preset") == true ||
intent.dataString?.startsWith("noice://preset") == true)
) {
intent.data?.also { PlaybackController.playPresetFromUri(this, it) }
}
}
override fun onDestroy() {
app.billingProvider.close()
super.onDestroy()
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
override fun onPending(skus: List<String>) {
Snackbar.make(binding.navHostFragment, R.string.payment_pending, Snackbar.LENGTH_LONG).show()
app.analyticsProvider.logEvent("purchase_pending", bundleOf())
}
override fun onComplete(skus: List<String>, orderId: String) {
app.analyticsProvider.logEvent("purchase_complete", bundleOf())
app.billingProvider.consumePurchase(orderId)
DialogFragment.show(supportFragmentManager) {
title(R.string.support_development__donate_thank_you)
message(R.string.support_development__donate_thank_you_description)
positiveButton(R.string.okay)
}
}
}

View File

@ -0,0 +1,65 @@
package com.github.ashutoshgngwr.noice.activity
import android.content.Intent
import android.content.pm.ShortcutManager
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.playback.PlaybackController
import com.github.ashutoshgngwr.noice.repository.PresetRepository
class ShortcutHandlerActivity : AppCompatActivity() {
companion object {
const val EXTRA_PRESET_ID = "preset_name"
const val EXTRA_SHORTCUT_ID = "shortcut_id"
/**
* Non-critical metadata; used for analytics.
*/
const val EXTRA_SHORTCUT_TYPE = "shortcut_type"
}
private val analyticsProvider by lazy { NoiceApplication.of(this).analyticsProvider }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val params = bundleOf()
intent.getStringExtra(EXTRA_PRESET_ID)?.also {
// id is passed with the intent. For app version <= 0.15.0, preset id was treated as shortcut
// id. Hence, using preset id as fallback in cases where shortcut id is null.
reportShortcutUsage(intent.getStringExtra(EXTRA_SHORTCUT_ID) ?: it)
if (PresetRepository.newInstance(this).get(it) == null) {
Toast.makeText(this, R.string.preset_does_not_exist, Toast.LENGTH_LONG).show()
params.putBoolean("success", false)
} else {
PlaybackController.playPreset(this, it)
params.putBoolean("success", true)
}
}
Intent(this, MainActivity::class.java)
.putExtra(MainActivity.EXTRA_NAV_DESTINATION, R.id.presets)
.also { startActivity(it) }
finish()
params.putString("shortcut_type", intent.getStringExtra(EXTRA_SHORTCUT_TYPE))
analyticsProvider.logEvent("preset_shortcut_open", params)
}
private fun reportShortcutUsage(shortcutID: String) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N_MR1) {
return
}
getSystemService(ShortcutManager::class.java).also {
it.reportShortcutUsed(shortcutID)
}
}
}

View File

@ -0,0 +1,14 @@
package com.github.ashutoshgngwr.noice.ext
import android.content.SharedPreferences
/**
* [getMutableStringSet] returns a mutable copy of the original [Set]<[String]> returned by
* [SharedPreferences.getStringSet]. If the [Set] isn't present in the [SharedPreferences], it
* returns an empty [MutableSet].
*
* @return [MutableSet]<[String]>
*/
fun SharedPreferences.getMutableStringSet(key: String): MutableSet<String> {
return getStringSet(key, null)?.toMutableSet() ?: mutableSetOf()
}

View File

@ -0,0 +1,80 @@
package com.github.ashutoshgngwr.noice.ext
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import androidx.core.os.HandlerCompat
import androidx.media.AudioAttributesCompat
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
private const val FADE_VOLUME_STEP = 0.001f
private val handler = Handler(Looper.getMainLooper())
/**
* Fade in and out effect for [SimpleExoPlayer].
*
* @param fromVolume initial volume where the fade transition will start
* @param toVolume final volume where the fade transition will end
* @param duration duration of fade in ms
* @param callback callback when fade transition finishes
*/
fun SimpleExoPlayer.fade(
fromVolume: Float,
toVolume: Float,
duration: Long,
callback: (() -> Unit)? = null
) {
// TODO: the code works for current requirements, but it is problematic. e.g. it cancels the
// previous transition (if on-going) when a new one is scheduled, thus also cancelling its
// callback. This behaviour might not be desired.
handler.removeCallbacksAndMessages(this)
if (!playWhenReady && !isPlaying) {
// edge case where fade is requested but playback is not playing.
volume = toVolume
callback?.invoke()
return
}
val sign = if (toVolume > fromVolume) 1 else -1
val steps = 1 + ceil(abs(toVolume - fromVolume) / FADE_VOLUME_STEP).toInt()
val period = duration / steps
volume = fromVolume
for (i in 0 until steps) {
HandlerCompat.postDelayed(
handler,
{ volume = max(0f, min(1f, volume + (sign * FADE_VOLUME_STEP))) },
this,
i * period
)
}
HandlerCompat.postDelayed(handler, {
volume = max(0f, min(1f, toVolume))
callback?.invoke()
}, this, duration + 50)
}
/**
* Implicitly translates [AudioAttributesCompat] to [AudioAttributes] and sets them on the provided
* [SimpleExoPlayer] receiver instance.
*/
fun SimpleExoPlayer.setAudioAttributesCompat(compatAttrs: AudioAttributesCompat) {
// internally, both implementations borrow their constants from `android.media`.
@SuppressLint("WrongConstant")
val attrs = AudioAttributes.Builder()
.setContentType(compatAttrs.contentType)
.setFlags(compatAttrs.flags)
.setUsage(compatAttrs.usage)
.build()
if (attrs != audioAttributes) {
audioAttributes = attrs
}
}

View File

@ -0,0 +1,26 @@
package com.github.ashutoshgngwr.noice.ext
import android.content.Context
import android.net.Uri
import androidx.browser.customtabs.CustomTabColorSchemeParams
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.res.ResourcesCompat
import com.github.ashutoshgngwr.noice.R
/**
* Launches the receiver [Uri] using an app themed [CustomTabsIntent].
*/
fun Uri.launchInCustomTab(context: Context) {
val tbColor = ResourcesCompat.getColor(context.resources, R.color.action_bar, context.theme)
val colorParams = CustomTabColorSchemeParams.Builder()
.setToolbarColor(tbColor)
.setNavigationBarColor(tbColor)
.build()
val customTabsIntent = CustomTabsIntent.Builder()
.setDefaultColorSchemeParams(colorParams)
.build()
customTabsIntent.launchUrl(context, this)
}

View File

@ -0,0 +1,123 @@
package com.github.ashutoshgngwr.noice.fragment
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import com.github.ashutoshgngwr.noice.BuildConfig
import com.github.ashutoshgngwr.noice.NoiceApplication
import com.github.ashutoshgngwr.noice.R
import com.github.ashutoshgngwr.noice.ext.launchInCustomTab
import mehdi.sakout.aboutpage.AboutPage
import mehdi.sakout.aboutpage.Element
class AboutFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return AboutPage(context).run {
setImage(R.drawable.app_banner)
setDescription(getString(R.string.app_description))
addItem(
buildElement(
R.drawable.ic_about_version,
"v${BuildConfig.VERSION_NAME}",
getString(R.string.app_changelog_url)
)
)
addItem(
buildElement(
R.drawable.ic_about_copyright,
R.string.app_copyright,
R.string.app_license_url
)
)
addItem(
buildElement(
R.drawable.ic_about_group,
R.string.app_authors,
R.string.app_authors_url
)
)
if (NoiceApplication.of(requireContext()).isGoogleMobileServicesAvailable()) {
addItem(
buildElement(
R.drawable.about_icon_google_play,
R.string.about_play_store,
R.string.play_store_url,
)
)
}
addItem(
buildElement(
R.drawable.about_icon_instagram,
R.string.about_instagram,
R.string.app_instagram_url
)
)
addItem(
buildElement(
R.drawable.about_icon_twitter,
R.string.about_twitter,
R.string.app_twitter_url
)
)
addItem(
buildElement(
R.drawable.about_icon_github,
R.string.about_github,
R.string.app_github_url
)
)
addItem(
buildElement(
R.drawable.about_icon_link,
R.string.about_website,
R.string.app_website_url
)
)
addGroup(getString(R.string.created_by))
addTwitter(creatorTwitter, creatorTwitter)
create()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
NoiceApplication.of(requireContext())
.analyticsProvider
.setCurrentScreen("about", AboutFragment::class)
}
private fun buildElement(
@DrawableRes iconId: Int,
@StringRes titleResId: Int,
@StringRes urlResId: Int
): Element {
return buildElement(iconId, getString(titleResId), getString(urlResId))
}
private fun buildElement(@DrawableRes iconId: Int, title: String, url: String): Element {
return Element(title, iconId)
.setAutoApplyIconTint(true)
.setOnClickListener { Uri.parse(url).launchInCustomTab(requireContext()) }
}
companion object {
private const val creatorTwitter = "ashutoshgngwr"
}
}

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