new icons
commit
1abf1a0a56
|
@ -0,0 +1,12 @@
|
|||
root = true
|
||||
|
||||
[*.{kt,kts}]
|
||||
|
||||
ktlint_code_style = android_studio
|
||||
max_line_length = 140
|
||||
|
||||
# Disable rules ktlint can't fix itself with spotlessApply
|
||||
ktlint_standard_no-wildcard-imports = disabled
|
||||
ktlint_standard_comment-wrapping = disabled
|
||||
ktlint_standard_property-naming = disabled
|
||||
ktlint_standard_discouraged-comment-location = disabled
|
|
@ -0,0 +1,34 @@
|
|||
# Gradle build files
|
||||
build/
|
||||
.gradle
|
||||
|
||||
# Local gradle properties
|
||||
local.properties
|
||||
|
||||
# IntelliJ .idea folder
|
||||
.idea/
|
||||
|
||||
gradle.xml
|
||||
markdown-*.xml
|
||||
*.iml
|
||||
|
||||
# General
|
||||
.DS_Store
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
|
||||
# Log Files
|
||||
*.log
|
||||
|
||||
# Android Studio Navigation editor temp files
|
||||
.navigation/
|
||||
|
||||
# Android Studio captures folder
|
||||
captures/
|
||||
|
||||
# Built application files
|
||||
*.apk
|
||||
*.aar
|
||||
|
||||
# Lineage test build keys
|
||||
lineage_keys/
|
|
@ -0,0 +1,93 @@
|
|||
stages:
|
||||
- lint
|
||||
- test
|
||||
- build
|
||||
|
||||
# By default load dev keys.
|
||||
variables:
|
||||
MAPBOX_KEY: $MAPBOX_KEY_DEV
|
||||
SENTRY_DSN: $SENTRY_DSN
|
||||
|
||||
default:
|
||||
image: "registry.gitlab.e.foundation/e/os/docker-android-apps-cicd:latest"
|
||||
before_script:
|
||||
- export GRADLE_USER_HOME=$(pwd)/.gradle
|
||||
- chmod +x ./gradlew
|
||||
#tags:
|
||||
# - android
|
||||
cache:
|
||||
key: ${CI_PROJECT_ID}
|
||||
paths:
|
||||
- .gradle/
|
||||
|
||||
lint:
|
||||
stage: lint
|
||||
script:
|
||||
- ./gradlew spotlessCheck
|
||||
- ./gradlew detekt
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
when: on_success
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
when: on_success
|
||||
artifacts:
|
||||
paths:
|
||||
- build/reports/detekt/
|
||||
|
||||
|
||||
# No unit tests yet.
|
||||
#unit-test:
|
||||
# stage: test
|
||||
# script:
|
||||
# - ./gradlew :testDebugUnitTest
|
||||
# rules:
|
||||
# - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
|
||||
# when: on_success
|
||||
# - if: $CI_COMMIT_BRANCH == "main"
|
||||
# when: on_success
|
||||
# artifacts:
|
||||
# paths:
|
||||
# - ./**/build/reports/tests/testDebugUnitTest
|
||||
|
||||
build-debug:
|
||||
stage: build
|
||||
script:
|
||||
- ./gradlew :app:assembleEosDebug
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
when: on_success
|
||||
artifacts:
|
||||
paths:
|
||||
- app/build/outputs/apk
|
||||
|
||||
# Check that the release build works, but don't keep the artifacts.
|
||||
build-release-test:
|
||||
stage: test
|
||||
script:
|
||||
- ./gradlew :app:assembleEosRelease
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main"
|
||||
variables:
|
||||
MAPBOX_KEY: $MAPBOX_KEY_PROD
|
||||
when: on_success
|
||||
|
||||
build-e-release:
|
||||
stage: build
|
||||
script:
|
||||
- ./gradlew :app:assembleEosRelease
|
||||
rules:
|
||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_PROTECTED == "true" && $CI_COMMIT_TAG =~ /^eOS-v\d+\.\d+(\.\d+)$/
|
||||
variables:
|
||||
MAPBOX_KEY: $MAPBOX_KEY_PROD
|
||||
when: on_success
|
||||
- if: $CI_COMMIT_REF_PROTECTED == "true"
|
||||
variables:
|
||||
MAPBOX_KEY: $MAPBOX_KEY_PROD
|
||||
when: manual
|
||||
|
||||
artifacts:
|
||||
paths:
|
||||
- app/build/outputs/apk
|
||||
- app/build/reports
|
|
@ -0,0 +1,3 @@
|
|||
[submodule "ipscrambling/orbotservice"]
|
||||
path = ipscrambling/orbotservice
|
||||
url = git@gitlab.e.foundation:e/os/orbotservice.git
|
Binary file not shown.
Binary file not shown.
|
@ -0,0 +1,90 @@
|
|||
# AdvancedPrivacy Development Guide
|
||||
This guide contains development related information to help a developer in getting better understanding of project structure.
|
||||
|
||||
## Architecture
|
||||
The architecture of AdvancedPrivacy is based on [clean architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html). For presentation layer, we use a MVVM design pattern,
|
||||
with a unique StateFlow<UiState> for each screen to simplify coherence. Our android app is having single activity multiple fragments, using Android Navigation component.
|
||||
|
||||
The project has 2 flavors :
|
||||
- eOS: for /e/OS devices, with OS specific signatures, system priviledges and persistent flag
|
||||
- standalone: for app's stores, without any priviledges.
|
||||
|
||||
Most of the differences between the 2 flavors are separated in distinct modules like :
|
||||
- permissioneos / permissionstandalone
|
||||
- trackersserviceseos / trackersservicesstandalone
|
||||
|
||||
### Clean Architecture
|
||||
|
||||
Clean architecture is the building block of AdvancedPrivacy. It is now a common way of organizing project,
|
||||
so it helps newcomers. It gives a framework to apply Single Responsibility Principle, having a testable project
|
||||
and keep files with a decent length.
|
||||
|
||||
|
||||
The detailed file tree:
|
||||
|
||||
**Domain**
|
||||
|
||||
- entities : data classes, with no logic
|
||||
- usecases : most of the logic, with no external dependencies
|
||||
|
||||
**LocalRepositories**
|
||||
|
||||
Repositories of data, that use local datasources, like sqlite database, sharedpreferences or in memory objects.
|
||||
|
||||
**NetworkRepositories**
|
||||
|
||||
Repositories of data, which fetch and push data to some remote servers.
|
||||
|
||||
**InterfaceAdapters**
|
||||
|
||||
All the glue to abstract Android framework (and also all it's supported versions) from the domain layer.
|
||||
|
||||
- services: Android Services
|
||||
- broadcastreceivers: Android Broadcast Receivers
|
||||
- Android Interfaces : abstraction of framework interfaces, like private and priviledges specific API.
|
||||
|
||||
**UI**
|
||||
All the UI related code, with MVVM pattern.
|
||||
|
||||
## Good practices
|
||||
|
||||
### Use hidden-apis-stubs
|
||||
|
||||
Reflexion is avoided. We use an [hidden-apis-stub](./permissionseos/libs/hidden-apis-stub) project to make Android hidden APIs available for development and compilations.
|
||||
Each stubed API should be documented with link to the source code they stub, for each targeted Android version.
|
||||
|
||||
### Use Coroutines and Flow
|
||||
|
||||
We use Coroutines and Flow for asynchronous tasks. The previous technologies (RxJava, LiveData) to do that are not welcome :)
|
||||
|
||||
### Use Koin for dependency injection
|
||||
|
||||
The project use Koin for "DI". It's flexibility is helpful to cleanly separate the flavored modules.
|
||||
|
||||
|
||||
## OrbotService development and maintenance
|
||||
|
||||
The IpScrambling relies on a fork of OrbotService, which is a module of Orbot, the Tor proxy for Android. It lays as a submodule to help fork upgrade and patching. More here: [orbotservice/README.md](orbotservice/README.md)
|
||||
|
||||
## Code Quality and Style
|
||||
|
||||
It use ktlint through spotless. The specific rules are defined in [.editorconfig](./.editorconfig).
|
||||
|
||||
To run code style check and formatting tool:
|
||||
```
|
||||
./gradlew spotlessCheck
|
||||
./gradlew spotlessApply
|
||||
```
|
||||
|
||||
If spotlessApply fails, let's discuss to relax the ktllint rules.
|
||||
|
||||
## State-of-The-Art
|
||||
|
||||
This document present the objectives for the project, some area may still have legacy code organizations.
|
||||
|
||||
### Todo/Improvements
|
||||
- [ ] Add unit tests and code coverage.
|
||||
|
||||
# References
|
||||
1. [Kotlin Flow](https://kotlinlang.org/docs/flow.html)
|
||||
4. [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
{one line to give the program's name and a brief idea of what it does.}
|
||||
Copyright (C) 2021 Amit Kumar
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
{project} Copyright (C) 2021 E Foundation
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1,161 @@
|
|||
# AdvancedPrivacy
|
||||
An app to let you control and protect your privacy.
|
||||
|
||||
Forked to https://github.com/LedgerProject/e_privacycentralapp, embending all /e/ submodules.
|
||||
|
||||
# Features
|
||||
The following features are currently part of AdvancedPrivacy app.
|
||||
1. Centralized overview dashboard.
|
||||
2. Fake location.
|
||||
3. Hiding IP address.
|
||||
4. Control trackers across apps.
|
||||
|
||||
# Technologies
|
||||
- Kotlin as main language
|
||||
- Kotlin coroutines and flow for asynchronous code
|
||||
- AndroidX (core-ktx, fragment-ktx, and lifecycle etc.)
|
||||
- Google Material Design component for UI elements
|
||||
- Timber for logging
|
||||
- MapLibre for map support
|
||||
- LeakCanary for keeping an eye on memory leaks.
|
||||
|
||||
# Flavours
|
||||
This app comes in two flavours, one for /e/OS and second one for other android (where app doesn't have system access)
|
||||
|
||||
# Testing
|
||||
Need to write test and add code coverage.
|
||||
|
||||
# Development
|
||||
|
||||
## Setup
|
||||
You can use any latest stable version of android studio to be able to build this app.
|
||||
|
||||
## Supported Versions
|
||||
- Minimum SDK: 26 (Android O)
|
||||
- Compile SDK: 34 (Android U)
|
||||
- Target SDK: 33 (Android T)
|
||||
|
||||
## API Keys
|
||||
This project uses [Sentry](https://sentry.io) for telemetry and crash reports, [Mapbox](https://docs.mapbox.com/android/maps/guides/install/) sdk as maps tiles provider. To compile the project, you need to set keys for them:
|
||||
|
||||
### For local build
|
||||
You can set them in local.properties
|
||||
```
|
||||
MAPBOX_KEY=<insert mapbox public key>
|
||||
SENTRY_DSN=<insert sentry dsn>
|
||||
```
|
||||
**IMP: Never add this file to version control.**
|
||||
|
||||
### For CI build
|
||||
When building in CI environment, we don't have local.properties file. So the following environment variables must be set:
|
||||
```
|
||||
export MAPBOX_KEY=<insert mapbox public key>
|
||||
export SENTRY_DSN=<insert sentry dsn>
|
||||
```
|
||||
|
||||
## Code Style and Quality
|
||||
This project uses [ktlint](https://github.com/pinterest/ktlint), provided via the [spotless](https://github.com/diffplug/spotless) gradle plugin. To maintain the same code style, all the codestyle configuration has been bundled into the project.
|
||||
|
||||
To check for any codestyle related error, `./gradlew spotlessCheck`. Use `./gradlew spotlessApply` to autoformat in order to fix any code quality related issues.
|
||||
|
||||
### Setting up pre-commit hooks
|
||||
To strictly enforce the code quality, this project has a pre-commit hook which is triggered everytime before you commit any changes (only applies to *.kt, *.gradle, *.md and *.gitignore). You must setup the pre-commit hook before doing any changes to the project. For that, this project has a script which can executed as follows:
|
||||
```bash
|
||||
./hooks/pre-commit
|
||||
```
|
||||
|
||||
## Build dependencies
|
||||
|
||||
Trackers filter and Fake location won't work unless your ROM was built with this specific netd project, android framework base and microG.
|
||||
|
||||
Custom netd project communicates to AdvancedPrivacy through a Unix socket, to log and block name resolution.
|
||||
|
||||
Custom android framework base and microG will consult the foundation.e.advancedprivacy.fakelocations ContentProvider for fake location instruction.
|
||||
|
||||
## Build
|
||||
If you'd like to build AdvancedPrivacy locally, you should be able to just clone and build with no issues.
|
||||
|
||||
For building from CLI, you can execute use `./gradlew assemble<Flavor><Debug|Release>` command:
|
||||
|
||||
Example for eOs debug version
|
||||
```bash
|
||||
./gradlew assembleEosDebug
|
||||
```
|
||||
|
||||
## How to use AdvancedPrivacy apk
|
||||
You can build the apk locally by using above instructions or you can download the latest stable apk from `master` branch pipeline.
|
||||
|
||||
### To run apk on /e/OS devices
|
||||
|
||||
If you are running your tests on a `/test` build, the debug buildtype already sign it with the appropriate key, and without the persistant flag, to allow further updates.
|
||||
But the first time, to replace the AdvancedPrivacy app, embeded in the test build, you have to use the following commands:
|
||||
|
||||
```shell
|
||||
adb root && adb remount
|
||||
adb push your_advanced_privacy_debug_build.apk /system/priv-app/AdvancedPrivacy/AdvancedPrivacy.apk
|
||||
adb shell kill -9 $(adb shell pidof -s foundation.e.advancedprivacy)
|
||||
```
|
||||
|
||||
#### AdvancedPrivacy requirement against the system
|
||||
|
||||
AdvancedPrivacy needs to be installed as system app and whitelisting in order to grant some system specific permissions. Follow these steps to make it work properly on /e/OS
|
||||
|
||||
1. From `Developer options`, enable `Android debugging` and `Rooted debugging`
|
||||
1. Sign the apk with platform certificate. You can use this command to do that
|
||||
|
||||
```shell
|
||||
apksigner sign --key platform.pk8 --cert platform.x509.pem AdvancedPrivacy.apk app-e-release-unsigned.apk
|
||||
```
|
||||
|
||||
If you are running your tests on an `/test` build, you can find keys at https://gitlab.e.foundation/e/os/android_build/-/tree/v1-q/target/product/security
|
||||
1. Install apk as system app and push permissions whitelist with following commands:
|
||||
```shell
|
||||
adb root && adb remount
|
||||
adb shell mkdir system/priv-app/AdvancedPrivacy
|
||||
adb push AdvancedPrivacy.apk system/priv-app/AdvancedPrivacy
|
||||
```
|
||||
|
||||
1. Push permissions whitelist.
|
||||
- it requires the whitelisting [privapp-permissions-foundation.e.advancedprivacy.xml](privapp-permissions-foundation.e.advancedprivacy.xml) file that can be found in the project repository.
|
||||
- then use the following command
|
||||
```bash
|
||||
adb push privapp-permissions-foundation.e.advancedprivacy.xml /system/etc/permissions/
|
||||
```
|
||||
|
||||
1. Allow the fake location service to run in background. Add <allow-in-power-save package="foundation.e.advancedprivacy" /> in the file /system/etc/permissions/platform.xml .
|
||||
|
||||
1. Reboot the device
|
||||
```shell
|
||||
adb reboot
|
||||
```
|
||||
|
||||
### To run apk on stock android devices
|
||||
You can simply install the apk. Keep in that mind all features won't be available on stock android devices.
|
||||
|
||||
> Voila !!!, AdvancedPrivacy is installed successfully in your device.
|
||||
|
||||
# Distribution
|
||||
This project can be distributed as prebuilt apk with /e/OS or it can be published on other app stores for non /e/OS devices.
|
||||
|
||||
# For developers and contributers
|
||||
Please refer to [Development Guide](DEVELOPMENT.md) for detailed instructions about project structure, architecture, design patterns and testing guide.
|
||||
|
||||
# License
|
||||
```
|
||||
Copyright (C) 2024 E FOUNDATION
|
||||
Copyright (C) 2023 MURENA SAS
|
||||
Copyright (C) 2021 ECORP
|
||||
|
||||
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/.
|
||||
```
|
|
@ -0,0 +1 @@
|
|||
/build
|
|
@ -0,0 +1,184 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
id 'kotlin-android'
|
||||
id 'kotlin-kapt'
|
||||
id 'androidx.navigation.safeargs.kotlin'
|
||||
}
|
||||
|
||||
def getSentryDsn = { ->
|
||||
|
||||
def sentryDsnEnv = System.getenv("SENTRY_DSN")
|
||||
if (sentryDsnEnv != null) {
|
||||
return sentryDsnEnv
|
||||
}
|
||||
|
||||
Properties properties = new Properties()
|
||||
def propertiesFile = project.rootProject.file('local.properties')
|
||||
if (propertiesFile.exists()) {
|
||||
properties.load(propertiesFile.newDataInputStream())
|
||||
}
|
||||
return properties.getProperty('SENTRY_DSN')
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion buildConfig.compileSdk
|
||||
|
||||
defaultConfig {
|
||||
applicationId "foundation.e.advancedprivacy"
|
||||
minSdkVersion buildConfig.minSdk
|
||||
targetSdkVersion buildConfig.targetSdk
|
||||
versionCode buildConfig.version.code
|
||||
versionName buildConfig.version.name
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
manifestPlaceholders = [
|
||||
persistent: "false",
|
||||
mainActivityIntentFilterCategory: "android.intent.category.LAUNCHER"
|
||||
]
|
||||
|
||||
resValue("string", "mapbox_key", MAPBOX_KEY)
|
||||
buildConfigField("String", "SENTRY_DSN", "\"${getSentryDsn()}\"")
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
debug {
|
||||
storeFile rootProject.file(".sign/debug.keystore")
|
||||
storePassword "android"
|
||||
keyAlias "androiddebugkey"
|
||||
keyPassword "android"
|
||||
}
|
||||
|
||||
// We use test platform keys to sign /e/OS specific debug flavour.
|
||||
eDebug {
|
||||
storeFile rootProject.file(".sign/platform.jks")
|
||||
storePassword "android"
|
||||
keyAlias "platform"
|
||||
keyPassword "android"
|
||||
}
|
||||
}
|
||||
|
||||
// We define here the OS flavor e, specific for the /e/ OS version, and google, for any
|
||||
// android device. The e or google prefix is then used in resources, dependencies, ... as
|
||||
// expected by the android gradle plugin.
|
||||
flavorDimensions 'os'
|
||||
productFlavors {
|
||||
eos {
|
||||
dimension 'os'
|
||||
signingConfig signingConfigs.eDebug
|
||||
}
|
||||
standalone {
|
||||
dimension 'os'
|
||||
applicationIdSuffix '.standalone'
|
||||
manifestPlaceholders = [
|
||||
persistent: "false",
|
||||
mainActivityIntentFilterCategory: "android.intent.category.LAUNCHER"
|
||||
]
|
||||
|
||||
signingConfig signingConfigs.debug
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
debug {
|
||||
signingConfig null // Set signing config to null as we use signingConfig per variant.
|
||||
}
|
||||
release {
|
||||
manifestPlaceholders = [
|
||||
persistent: "true",
|
||||
mainActivityIntentFilterCategory: "android.intent.category.INFO"
|
||||
]
|
||||
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the output name of the variant outputs and also it setup signingConfig based on the product flavor.
|
||||
*/
|
||||
applicationVariants.all { variant ->
|
||||
variant.outputs.all { output ->
|
||||
outputFileName = "Advanced_Privacy-${variant.versionName}-${variant.getFlavorName()}-${variant.buildType.name}.apk"
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
dataBinding true
|
||||
viewBinding true
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
disable 'MissingTranslation'
|
||||
}
|
||||
namespace 'foundation.e.advancedprivacy'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':core')
|
||||
standaloneImplementation project(':permissionsstandalone')
|
||||
eosImplementation project(':permissionseos')
|
||||
|
||||
eosImplementation files('libs/lineage-sdk.jar')
|
||||
|
||||
implementation project(':trackers')
|
||||
|
||||
implementation project(':ipscrambling')
|
||||
eosImplementation project(':trackersserviceeos')
|
||||
standaloneImplementation project(':trackersservicestandalone')
|
||||
|
||||
implementation (
|
||||
libs.androidx.core.ktx,
|
||||
libs.androidx.appcompat,
|
||||
libs.androidx.datastore.preferences,
|
||||
libs.androidx.fragment.ktx,
|
||||
libs.androidx.lifecycle.runtime,
|
||||
libs.androidx.lifecycle.viewmodel,
|
||||
libs.androidx.navigation.fragment,
|
||||
libs.androidx.navigation.ui,
|
||||
libs.androidx.viewpager2,
|
||||
|
||||
libs.bundles.koin,
|
||||
|
||||
libs.eos.elib,
|
||||
libs.eos.telemetry,
|
||||
|
||||
libs.google.material,
|
||||
|
||||
libs.maplibre,
|
||||
libs.mpandroidcharts,
|
||||
|
||||
libs.timber
|
||||
)
|
||||
|
||||
debugImplementation libs.leakcanary
|
||||
|
||||
testImplementation libs.junit
|
||||
}
|
||||
|
||||
static def log(Object val) {
|
||||
println("[GradleRepository]: " + val)
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"version": 3,
|
||||
"artifactType": {
|
||||
"type": "APK",
|
||||
"kind": "Directory"
|
||||
},
|
||||
"applicationId": "foundation.e.advancedprivacy",
|
||||
"variantName": "eosRelease",
|
||||
"elements": [
|
||||
{
|
||||
"type": "SINGLE",
|
||||
"filters": [],
|
||||
"attributes": [],
|
||||
"versionCode": 2005000,
|
||||
"versionName": "2.5.0",
|
||||
"outputFile": "Advanced_Privacy-2.5.0-eos-release.apk"
|
||||
}
|
||||
],
|
||||
"elementType": "File"
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,21 @@
|
|||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
|
@ -0,0 +1,106 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright (C) 2022 ECORP, 2022 MURENA SAS
|
||||
|
||||
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/>.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_SECURE_SETTINGS"
|
||||
tools:ignore="ProtectedPermissions"
|
||||
/>
|
||||
<uses-permission
|
||||
android:name="android.permission.INTERACT_ACROSS_USERS_FULL"
|
||||
tools:ignore="ProtectedPermissions"
|
||||
/>
|
||||
<uses-permission android:name="lineageos.permission.ACCESS_BLOCKER" />
|
||||
<uses-permission
|
||||
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||
tools:ignore="QueryAllPackagesPermission"
|
||||
/>
|
||||
|
||||
<uses-permission android:name="foundation.e.permission.READ_FAKE_LOCATION_SETTINGS" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:icon="@drawable/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:name="foundation.e.advancedprivacy.AdvancedPrivacyApplication"
|
||||
android:persistent="${persistent}"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.AdvancedPrivacy"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
tools:replace="android:icon,android:label,android:theme"
|
||||
>
|
||||
|
||||
<provider
|
||||
android:name=".externalinterfaces.contentproviders.FakeLocationContentProvider"
|
||||
android:authorities="foundation.e.advancedprivacy.fakelocations"
|
||||
android:permission="foundation.e.permission.READ_FAKE_LOCATION_SETTINGS"
|
||||
android:enabled="true"
|
||||
android:exported="true"
|
||||
/>
|
||||
|
||||
<receiver
|
||||
android:name="foundation.e.advancedprivacy.common.BootCompletedReceiver"
|
||||
android:exported="true"
|
||||
>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver
|
||||
android:exported="true"
|
||||
android:name="foundation.e.advancedprivacy.Widget"
|
||||
>
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
android:resource="@xml/widget_info"
|
||||
/>
|
||||
</receiver>
|
||||
<receiver android:name="foundation.e.advancedprivacy.widget.WidgetCommandReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="toggle_privacy" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<activity android:name="foundation.e.advancedprivacy.main.MainActivity"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true"
|
||||
>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="${mainActivityIntentFilterCategory}"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity
|
||||
android:name="foundation.e.advancedprivacy.common.WarningDialog"
|
||||
android:noHistory="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleInstance"
|
||||
android:theme="@style/Theme.InvisibleActivity"
|
||||
/>
|
||||
</application>
|
||||
</manifest>
|
File diff suppressed because one or more lines are too long
Binary file not shown.
After Width: | Height: | Size: 88 KiB |
|
@ -0,0 +1,77 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2023 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy
|
||||
|
||||
import android.app.Application
|
||||
import foundation.e.advancedprivacy.common.WarningDialog
|
||||
import foundation.e.advancedprivacy.domain.usecases.FakeLocationStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.IpScramblingStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.ShowFeaturesWarningUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.VpnSupervisorUseCase
|
||||
import foundation.e.advancedprivacy.externalinterfaces.permissions.IPermissionsPrivacyModule
|
||||
import foundation.e.advancedprivacy.trackers.services.UpdateTrackersWorker
|
||||
import foundation.e.lib.telemetry.Telemetry
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.core.context.startKoin
|
||||
import org.koin.java.KoinJavaComponent.get
|
||||
|
||||
class AdvancedPrivacyApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Telemetry.init(BuildConfig.SENTRY_DSN, this, true)
|
||||
|
||||
startKoin {
|
||||
androidContext(this@AdvancedPrivacyApplication)
|
||||
modules(appModule)
|
||||
}
|
||||
initBackgroundSingletons()
|
||||
}
|
||||
|
||||
private fun initBackgroundSingletons() {
|
||||
UpdateTrackersWorker.periodicUpdate(this)
|
||||
|
||||
WarningDialog.startListening(
|
||||
get(ShowFeaturesWarningUseCase::class.java),
|
||||
get(CoroutineScope::class.java),
|
||||
this
|
||||
)
|
||||
|
||||
Widget.startListening(
|
||||
this,
|
||||
get(GetQuickPrivacyStateUseCase::class.java),
|
||||
get(TrackersStatisticsUseCase::class.java)
|
||||
)
|
||||
|
||||
Notifications.startListening(
|
||||
this,
|
||||
get(GetQuickPrivacyStateUseCase::class.java),
|
||||
get(IPermissionsPrivacyModule::class.java),
|
||||
get(CoroutineScope::class.java)
|
||||
)
|
||||
|
||||
get<IpScramblingStateUseCase>(IpScramblingStateUseCase::class.java)
|
||||
get<TrackersStateUseCase>(TrackersStateUseCase::class.java)
|
||||
get<FakeLocationStateUseCase>(FakeLocationStateUseCase::class.java)
|
||||
get<VpnSupervisorUseCase>(VpnSupervisorUseCase::class.java).listenSettings()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,204 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy
|
||||
|
||||
import android.content.res.Resources
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Process
|
||||
import foundation.e.advancedprivacy.core.coreModule
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.data.repositories.LocalStateRepositoryImpl
|
||||
import foundation.e.advancedprivacy.data.repositories.ResourcesRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.ProfileType
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import foundation.e.advancedprivacy.domain.usecases.AppTrackersUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.FakeLocationForAppUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.FakeLocationStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.IpScramblingStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.ListenLocationUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.ShowFeaturesWarningUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackerDetailsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersAndAppsListsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersScreenUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.dummy.CityDataSource
|
||||
import foundation.e.advancedprivacy.externalinterfaces.permissions.IPermissionsPrivacyModule
|
||||
import foundation.e.advancedprivacy.features.dashboard.DashboardViewModel
|
||||
import foundation.e.advancedprivacy.features.internetprivacy.InternetPrivacyViewModel
|
||||
import foundation.e.advancedprivacy.features.location.FakeLocationViewModel
|
||||
import foundation.e.advancedprivacy.features.trackers.Period
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackersPeriodViewModel
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackersViewModel
|
||||
import foundation.e.advancedprivacy.features.trackers.apptrackers.AppTrackersViewModel
|
||||
import foundation.e.advancedprivacy.features.trackers.trackerdetails.TrackerDetailsViewModel
|
||||
import foundation.e.advancedprivacy.ipscrambler.ipScramblerModule
|
||||
import foundation.e.advancedprivacy.permissions.externalinterfaces.PermissionsPrivacyModuleImpl
|
||||
import foundation.e.advancedprivacy.trackers.data.TrackersRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import foundation.e.advancedprivacy.trackers.service.trackerServiceModule
|
||||
import foundation.e.advancedprivacy.trackers.trackersModule
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import org.koin.android.ext.koin.androidContext
|
||||
import org.koin.androidx.viewmodel.dsl.viewModel
|
||||
import org.koin.androidx.viewmodel.dsl.viewModelOf
|
||||
import org.koin.core.module.dsl.singleOf
|
||||
import org.koin.core.qualifier.named
|
||||
import org.koin.dsl.module
|
||||
import timber.log.Timber
|
||||
|
||||
val appModule = module {
|
||||
includes(coreModule, trackersModule, ipScramblerModule, trackerServiceModule)
|
||||
|
||||
single<CoroutineScope> {
|
||||
CoroutineScope(
|
||||
SupervisorJob() +
|
||||
Dispatchers.IO +
|
||||
CoroutineExceptionHandler { _, throwable ->
|
||||
Timber.e(throwable, "Uncaught error in backgroundScope")
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
factory<Resources> { androidContext().resources }
|
||||
single<LocalStateRepository> {
|
||||
LocalStateRepositoryImpl(context = androidContext())
|
||||
}
|
||||
|
||||
single<ApplicationDescription>(named("AdvancedPrivacy")) {
|
||||
ApplicationDescription(
|
||||
packageName = androidContext().packageName,
|
||||
uid = Process.myUid(),
|
||||
label = androidContext().resources.getString(R.string.app_name),
|
||||
icon = null,
|
||||
profileId = -1,
|
||||
profileType = ProfileType.MAIN
|
||||
)
|
||||
}
|
||||
|
||||
single<CharSequence>(named("SystemAppLabel")) {
|
||||
androidContext().getString(R.string.dummy_system_app_label)
|
||||
}
|
||||
single<Drawable>(named("SystemAppIcon")) {
|
||||
androidContext().getDrawable(R.drawable.ic_e_app_logo)!!
|
||||
}
|
||||
|
||||
single<CharSequence>(named("CompatibilityAppLabel")) {
|
||||
androidContext().getString(R.string.dummy_apps_compatibility_app_label)
|
||||
}
|
||||
single<Drawable>(named("CompatibilityAppIcon")) {
|
||||
androidContext().getDrawable(R.drawable.ic_apps_compatibility_components)!!
|
||||
}
|
||||
|
||||
single { CityDataSource }
|
||||
single { ResourcesRepository(androidContext()) }
|
||||
|
||||
singleOf(::FakeLocationStateUseCase)
|
||||
|
||||
single {
|
||||
ListenLocationUseCase(
|
||||
permissionsModule = get(),
|
||||
appDesc = get(named("AdvancedPrivacy")),
|
||||
appContext = androidContext()
|
||||
)
|
||||
}
|
||||
|
||||
singleOf(::FakeLocationForAppUseCase)
|
||||
|
||||
singleOf(::GetQuickPrivacyStateUseCase)
|
||||
single {
|
||||
IpScramblingStateUseCase(
|
||||
orbotSupervisor = get(),
|
||||
localStateRepository = get(),
|
||||
appListRepository = get(),
|
||||
backgroundScope = get()
|
||||
)
|
||||
}
|
||||
|
||||
singleOf(::ShowFeaturesWarningUseCase)
|
||||
singleOf(::TrackersStateUseCase)
|
||||
singleOf(::TrackersStatisticsUseCase)
|
||||
singleOf(::TrackersAndAppsListsUseCase)
|
||||
|
||||
singleOf(::AppTrackersUseCase)
|
||||
singleOf(::TrackerDetailsUseCase)
|
||||
single {
|
||||
TrackersScreenUseCase(localStateRepository = get())
|
||||
}
|
||||
|
||||
single<IPermissionsPrivacyModule> {
|
||||
PermissionsPrivacyModuleImpl(context = androidContext())
|
||||
}
|
||||
|
||||
viewModel { parameters ->
|
||||
val appListRepository: AppListRepository = get()
|
||||
val app = appListRepository.getAppById(parameters.get()) ?: DisplayableApp(
|
||||
id = "dummy-app",
|
||||
label = androidContext().resources.getString(R.string.app_name),
|
||||
icon = get(named("SystemAppIcon")),
|
||||
apps = setOf(get(named("AdvancedPrivacy"))),
|
||||
hasLocationPermission = true,
|
||||
hasInternetPermission = true,
|
||||
profileType = ProfileType.MAIN
|
||||
)
|
||||
|
||||
AppTrackersViewModel(
|
||||
app = app,
|
||||
trackersStateUseCase = get(),
|
||||
trackersStatisticsUseCase = get(),
|
||||
getQuickPrivacyStateUseCase = get(),
|
||||
appTrackersUseCase = get()
|
||||
)
|
||||
}
|
||||
|
||||
viewModel { parameters ->
|
||||
val trackersRepository: TrackersRepository = get()
|
||||
val tracker = trackersRepository.getTracker(parameters.get()) ?: Tracker("-1", emptySet(), "dummy", null)
|
||||
|
||||
TrackerDetailsViewModel(
|
||||
tracker = tracker,
|
||||
trackersStateUseCase = get(),
|
||||
trackersStatisticsUseCase = get(),
|
||||
getQuickPrivacyStateUseCase = get(),
|
||||
trackerDetailsUseCase = get()
|
||||
)
|
||||
}
|
||||
|
||||
viewModel { parameters ->
|
||||
|
||||
val period: Period = runCatching { Period.valueOf(parameters.get()) }.getOrDefault(Period.DAY)
|
||||
|
||||
TrackersPeriodViewModel(
|
||||
period = period,
|
||||
trackersStatisticsUseCase = get(),
|
||||
trackersAndAppsListsUseCase = get(),
|
||||
trackersScreenUseCase = get()
|
||||
)
|
||||
}
|
||||
|
||||
viewModelOf(::TrackersViewModel)
|
||||
viewModelOf(::FakeLocationViewModel)
|
||||
viewModelOf(::InternetPrivacyViewModel)
|
||||
viewModelOf(::DashboardViewModel)
|
||||
}
|
|
@ -0,0 +1,190 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2022 - 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import foundation.e.advancedprivacy.core.utils.notificationBuilder
|
||||
import foundation.e.advancedprivacy.domain.entities.CHANNEL_FAKE_LOCATION_FLAG
|
||||
import foundation.e.advancedprivacy.domain.entities.CHANNEL_FIRST_BOOT
|
||||
import foundation.e.advancedprivacy.domain.entities.CHANNEL_IPSCRAMBLING_FLAG
|
||||
import foundation.e.advancedprivacy.domain.entities.CHANNEL_TRACKER_FLAG
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.entities.NOTIFICATION_FAKE_LOCATION_FLAG
|
||||
import foundation.e.advancedprivacy.domain.entities.NOTIFICATION_FIRST_BOOT
|
||||
import foundation.e.advancedprivacy.domain.entities.NOTIFICATION_IPSCRAMBLING_FLAG
|
||||
import foundation.e.advancedprivacy.domain.entities.NotificationContent
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.externalinterfaces.permissions.IPermissionsPrivacyModule
|
||||
import foundation.e.advancedprivacy.main.MainActivity
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
|
||||
object Notifications {
|
||||
fun showFirstBootNotification(context: Context) {
|
||||
createNotificationFirstBootChannel(context)
|
||||
val notificationBuilder: NotificationCompat.Builder = notificationBuilder(
|
||||
context,
|
||||
NotificationContent(
|
||||
channelId = CHANNEL_FIRST_BOOT,
|
||||
icon = R.drawable.ic_notification_logo,
|
||||
title = R.string.first_notification_title,
|
||||
description = R.string.first_notification_summary,
|
||||
pendingIntent = MainActivity.deepLinkBuilder(context)
|
||||
.setDestination(R.id.dashboardFragment)
|
||||
.createPendingIntent()
|
||||
)
|
||||
)
|
||||
.setAutoCancel(true)
|
||||
|
||||
NotificationManagerCompat.from(context).notify(
|
||||
NOTIFICATION_FIRST_BOOT,
|
||||
notificationBuilder.build()
|
||||
)
|
||||
}
|
||||
|
||||
fun startListening(
|
||||
appContext: Context,
|
||||
getQuickPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
|
||||
permissionsPrivacyModule: IPermissionsPrivacyModule,
|
||||
appScope: CoroutineScope
|
||||
) {
|
||||
createNotificationFlagChannel(
|
||||
context = appContext,
|
||||
permissionsPrivacyModule = permissionsPrivacyModule,
|
||||
channelId = CHANNEL_FAKE_LOCATION_FLAG,
|
||||
channelName = R.string.notifications_fake_location_channel_name,
|
||||
channelDescription = R.string.notifications_fake_location_channel_description
|
||||
)
|
||||
|
||||
createNotificationFlagChannel(
|
||||
context = appContext,
|
||||
permissionsPrivacyModule = permissionsPrivacyModule,
|
||||
channelId = CHANNEL_IPSCRAMBLING_FLAG,
|
||||
channelName = R.string.notifications_ipscrambling_channel_name,
|
||||
channelDescription = R.string.notifications_ipscrambling_channel_description
|
||||
)
|
||||
|
||||
createNotificationFlagChannel(
|
||||
context = appContext,
|
||||
permissionsPrivacyModule = permissionsPrivacyModule,
|
||||
channelId = CHANNEL_TRACKER_FLAG,
|
||||
channelName = R.string.notifications_tracker_channel_name,
|
||||
channelDescription = R.string.notifications_tracker_channel_description
|
||||
)
|
||||
|
||||
getQuickPrivacyStateUseCase.locationMode.map {
|
||||
it != FeatureMode.VULNERABLE
|
||||
}.distinctUntilChanged().onEach {
|
||||
if (it) {
|
||||
showFlagNotification(appContext, NOTIFICATION_FAKE_LOCATION_FLAG)
|
||||
} else {
|
||||
hideFlagNotification(appContext, NOTIFICATION_FAKE_LOCATION_FLAG)
|
||||
}
|
||||
}.launchIn(appScope)
|
||||
|
||||
getQuickPrivacyStateUseCase.ipScramblingMode.map {
|
||||
it != FeatureState.OFF
|
||||
}.distinctUntilChanged().onEach {
|
||||
if (it) {
|
||||
showFlagNotification(appContext, NOTIFICATION_IPSCRAMBLING_FLAG)
|
||||
} else {
|
||||
hideFlagNotification(appContext, NOTIFICATION_IPSCRAMBLING_FLAG)
|
||||
}
|
||||
}.launchIn(appScope)
|
||||
}
|
||||
|
||||
private fun createNotificationFirstBootChannel(context: Context) {
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_FIRST_BOOT,
|
||||
context.getString(R.string.notifications_first_boot_channel_name),
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
)
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun createNotificationFlagChannel(
|
||||
context: Context,
|
||||
permissionsPrivacyModule: IPermissionsPrivacyModule,
|
||||
channelId: String,
|
||||
@StringRes channelName: Int,
|
||||
@StringRes channelDescription: Int
|
||||
) {
|
||||
val channel = NotificationChannel(
|
||||
channelId,
|
||||
context.getString(channelName),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
)
|
||||
channel.description = context.getString(channelDescription)
|
||||
permissionsPrivacyModule.setBlockable(channel)
|
||||
NotificationManagerCompat.from(context).createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
private fun showFlagNotification(context: Context, id: Int) {
|
||||
when (id) {
|
||||
NOTIFICATION_FAKE_LOCATION_FLAG -> showFlagNotification(
|
||||
context = context,
|
||||
id = NOTIFICATION_FAKE_LOCATION_FLAG,
|
||||
content = NotificationContent(
|
||||
channelId = CHANNEL_FAKE_LOCATION_FLAG,
|
||||
icon = R.drawable.ic_fmd_bad,
|
||||
title = R.string.notifications_fake_location_title,
|
||||
description = R.string.notifications_fake_location_content,
|
||||
pendingIntent = MainActivity.deepLinkBuilder(context)
|
||||
.addDestination(R.id.fakeLocationFragment)
|
||||
.createPendingIntent()
|
||||
)
|
||||
)
|
||||
NOTIFICATION_IPSCRAMBLING_FLAG -> showFlagNotification(
|
||||
context = context,
|
||||
id = NOTIFICATION_IPSCRAMBLING_FLAG,
|
||||
content = NotificationContent(
|
||||
channelId = CHANNEL_IPSCRAMBLING_FLAG,
|
||||
icon = R.drawable.ic_language,
|
||||
title = R.string.notifications_ipscrambling_title,
|
||||
description = R.string.notifications_ipscrambling_content,
|
||||
pendingIntent = MainActivity.deepLinkBuilder(context)
|
||||
.addDestination(R.id.internetPrivacyFragment)
|
||||
.createPendingIntent()
|
||||
)
|
||||
)
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showFlagNotification(context: Context, id: Int, content: NotificationContent) {
|
||||
val builder = notificationBuilder(context, content)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.setOngoing(true)
|
||||
|
||||
NotificationManagerCompat.from(context).notify(id, builder.build())
|
||||
}
|
||||
|
||||
private fun hideFlagNotification(context: Context, id: Int) {
|
||||
NotificationManagerCompat.from(context).cancel(id)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
/*
|
||||
* Copyright (C) 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.content.Context
|
||||
import android.icu.number.NumberFormatter
|
||||
|
||||
class BigNumberFormatter(context: Context) {
|
||||
private val formatter = NumberFormatter.withLocale(context.resources.configuration.locales[0])
|
||||
|
||||
fun format(number: Int): CharSequence = formatter.format(number)
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
/*
|
||||
* Copyright (C) 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewbinding.ViewBinding
|
||||
|
||||
class BindingViewHolder<T : ViewBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)
|
||||
|
||||
abstract class BindingListAdapter<T : ViewBinding, U> : RecyclerView.Adapter<BindingViewHolder<T>>() {
|
||||
var dataSet: List<U> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = dataSet.size
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import foundation.e.advancedprivacy.Notifications
|
||||
import foundation.e.advancedprivacy.core.utils.goAsync
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import org.koin.java.KoinJavaComponent.inject
|
||||
|
||||
class BootCompletedReceiver : BroadcastReceiver() {
|
||||
|
||||
private val localStateRepository by inject<LocalStateRepository>(LocalStateRepository::class.java)
|
||||
private val backgroundScope by inject<CoroutineScope>(CoroutineScope::class.java)
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent?) {
|
||||
if (intent?.action == Intent.ACTION_BOOT_COMPLETED) {
|
||||
goAsync(backgroundScope) {
|
||||
if (localStateRepository.isFirstBoot()) {
|
||||
Notifications.showFirstBootNotification(context)
|
||||
localStateRepository.setFirstBoot(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import foundation.e.advancedprivacy.BuildConfig
|
||||
|
||||
const val isStandaloneBuild: Boolean = BuildConfig.FLAVOR == "standalone"
|
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import androidx.annotation.LayoutRes
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import com.google.android.material.appbar.MaterialToolbar
|
||||
import foundation.e.advancedprivacy.R
|
||||
|
||||
abstract class NavToolbarFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) {
|
||||
|
||||
/**
|
||||
* @return title to be used in toolbar
|
||||
*/
|
||||
open fun getTitle(): CharSequence {
|
||||
return findNavController().currentDestination?.label ?: ""
|
||||
}
|
||||
|
||||
fun setTitle(title: CharSequence?) {
|
||||
getToolbar()?.title = title
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
view.findViewById<MaterialToolbar>(R.id.toolbar).let { toolbar ->
|
||||
toolbar.title = getTitle()
|
||||
toolbar.setNavigationOnClickListener {
|
||||
onNavigateUp()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
open fun onNavigateUp(): Boolean {
|
||||
return findNavController().navigateUp()
|
||||
}
|
||||
|
||||
fun getToolbar(): MaterialToolbar? = view?.findViewById(R.id.toolbar)
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import android.widget.RadioButton
|
||||
|
||||
/**
|
||||
* A custom [RadioButton] which displays the radio drawable on the right side.
|
||||
*/
|
||||
@SuppressLint("AppCompatCustomView")
|
||||
class RightRadioButton : RadioButton {
|
||||
|
||||
constructor(context: Context) : super(context)
|
||||
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
|
||||
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
|
||||
context,
|
||||
attrs,
|
||||
defStyleAttr
|
||||
)
|
||||
|
||||
// Returns layout direction as right-to-left to draw the compound button on right side.
|
||||
override fun getLayoutDirection(): Int {
|
||||
return LAYOUT_DIRECTION_RTL
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.DynamicDrawableSpan
|
||||
import android.text.style.ImageSpan
|
||||
import android.widget.TextView
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.appcompat.content.res.AppCompatResources
|
||||
import androidx.appcompat.widget.TooltipCompat
|
||||
import foundation.e.advancedprivacy.R
|
||||
|
||||
fun setToolTipForAsterisk(textView: TextView, @StringRes textId: Int, @StringRes tooltipTextId: Int) {
|
||||
textView.text = asteriskAsInfoIconSpannable(textView.context, textId, textView.textColors)
|
||||
TooltipCompat.setTooltipText(textView, textView.context.getString(tooltipTextId))
|
||||
|
||||
textView.setOnClickListener { it.performLongClick() }
|
||||
}
|
||||
|
||||
private fun asteriskAsInfoIconSpannable(context: Context, @StringRes textId: Int, tint: ColorStateList): Spannable {
|
||||
val spannable = SpannableString(context.getString(textId))
|
||||
val index = spannable.lastIndexOf("*")
|
||||
if (index != -1) {
|
||||
AppCompatResources.getDrawable(context, R.drawable.ic_info_16dp)?.let {
|
||||
it.setTintList(tint)
|
||||
it.setBounds(0, 0, it.intrinsicWidth, it.intrinsicHeight)
|
||||
spannable.setSpan(
|
||||
ImageSpan(it, DynamicDrawableSpan.ALIGN_CENTER),
|
||||
index,
|
||||
index + 1,
|
||||
Spannable.SPAN_INCLUSIVE_INCLUSIVE
|
||||
)
|
||||
}
|
||||
}
|
||||
return spannable
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
/*
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import kotlin.time.Duration
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
|
||||
@FlowPreview
|
||||
fun <T> Flow<T>.throttleFirst(windowDuration: Duration): Flow<T> = flow {
|
||||
var lastEmissionTime = 0L
|
||||
collect { upstream ->
|
||||
val currentTime = System.currentTimeMillis()
|
||||
val mayEmit = currentTime - lastEmissionTime > windowDuration.inWholeMilliseconds
|
||||
if (mayEmit) {
|
||||
lastEmissionTime = currentTime
|
||||
emit(upstream)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,166 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.CheckBox
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.FakeLocation
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.IpScrambling
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.TrackersControl
|
||||
import foundation.e.advancedprivacy.domain.usecases.ShowFeaturesWarningUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.VpnSupervisorUseCase
|
||||
import foundation.e.advancedprivacy.main.MainActivity
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.koin.android.ext.android.inject
|
||||
import org.koin.java.KoinJavaComponent.get
|
||||
import timber.log.Timber
|
||||
|
||||
class WarningDialog : AppCompatActivity() {
|
||||
companion object {
|
||||
private const val PARAM_FEATURE = "feature"
|
||||
|
||||
fun startListening(showFeaturesWarningUseCase: ShowFeaturesWarningUseCase, appScope: CoroutineScope, appContext: Context) {
|
||||
showFeaturesWarningUseCase.showWarning().map { feature ->
|
||||
appContext.startActivity(
|
||||
createIntent(context = appContext, feature = feature)
|
||||
)
|
||||
}.launchIn(appScope)
|
||||
}
|
||||
|
||||
private fun createIntent(context: Context, feature: MainFeatures): Intent {
|
||||
val intent = Intent(context, WarningDialog::class.java)
|
||||
intent.putExtra(PARAM_FEATURE, feature)
|
||||
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
return intent
|
||||
}
|
||||
}
|
||||
|
||||
private val showFeaturesWarningUseCase: ShowFeaturesWarningUseCase by inject()
|
||||
private val vpnSupervisorUseCase: VpnSupervisorUseCase by inject()
|
||||
|
||||
private var isWaitingForResult = false
|
||||
private lateinit var feature: MainFeatures
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.setBackgroundDrawable(ColorDrawable(0))
|
||||
|
||||
feature = try {
|
||||
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
|
||||
intent.getParcelableExtra(PARAM_FEATURE, MainFeatures::class.java)!!
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(PARAM_FEATURE)!!
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e, "Missing mandatory activity parameter")
|
||||
finish()
|
||||
return
|
||||
}
|
||||
showWarningDialog(feature)
|
||||
}
|
||||
|
||||
private fun showWarningDialog(feature: MainFeatures) {
|
||||
val builder = AlertDialog.Builder(this)
|
||||
builder.setOnDismissListener { if (!isWaitingForResult) finish() }
|
||||
|
||||
val content: View = layoutInflater.inflate(R.layout.alertdialog_do_not_show_again, null)
|
||||
val checkbox = content.findViewById<CheckBox>(R.id.checkbox)
|
||||
builder.setView(content)
|
||||
|
||||
builder.setMessage(
|
||||
when (feature) {
|
||||
is TrackersControl -> R.string.warningdialog_trackers_message
|
||||
is FakeLocation -> R.string.warningdialog_location_message
|
||||
is IpScrambling -> R.string.warningdialog_ipscrambling_message
|
||||
}
|
||||
)
|
||||
|
||||
builder.setTitle(
|
||||
when (feature) {
|
||||
is TrackersControl -> R.string.warningdialog_trackers_title
|
||||
is FakeLocation -> R.string.warningdialog_location_title
|
||||
is IpScrambling -> R.string.warningdialog_ipscrambling_title
|
||||
}
|
||||
)
|
||||
|
||||
builder.setPositiveButton(
|
||||
when (feature) {
|
||||
is IpScrambling -> R.string.warningdialog_ipscrambling_cta
|
||||
else -> R.string.ok
|
||||
}
|
||||
) { _, _ ->
|
||||
lifecycleScope.launch {
|
||||
if (checkbox.isChecked) {
|
||||
withContext(Dispatchers.IO) {
|
||||
showFeaturesWarningUseCase.doNotShowAgain(feature)
|
||||
}
|
||||
}
|
||||
|
||||
val vpnDisclaimerIntent = (feature as? IpScrambling)?.startVpnDisclaimer
|
||||
|
||||
if (vpnDisclaimerIntent != null) {
|
||||
isWaitingForResult = true
|
||||
launchAndroidVpnDisclaimer.launch(vpnDisclaimerIntent)
|
||||
} else {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (feature is TrackersControl) {
|
||||
builder.setNeutralButton(R.string.warningdialog_trackers_secondary_cta) { _, _ ->
|
||||
MainActivity.deepLinkBuilder(this)
|
||||
.setDestination(R.id.trackersFragment)
|
||||
.createPendingIntent().send()
|
||||
|
||||
finish()
|
||||
}
|
||||
}
|
||||
builder.show()
|
||||
}
|
||||
|
||||
private val launchAndroidVpnDisclaimer = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
lifecycleScope.launch {
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
vpnSupervisorUseCase.startVpnService(feature)
|
||||
} else {
|
||||
vpnSupervisorUseCase.cancelStartVpnService(feature)
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
/*
|
||||
* Copyright (C) 2024 MURENA SAS
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.common.extensions
|
||||
|
||||
import android.content.Context
|
||||
|
||||
fun Int.dpToPxF(context: Context): Float = this.toFloat() * context.resources.displayMetrics.density
|
||||
|
||||
fun Int.dpToPx(context: Context): Int = (this * context.resources.displayMetrics.density).toInt()
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.common.extensions
|
||||
|
||||
import android.view.View
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
|
||||
fun ViewPager2.findViewHolderForAdapterPosition(position: Int): RecyclerView.ViewHolder? {
|
||||
return (getChildAt(0) as RecyclerView).findViewHolderForAdapterPosition(position)
|
||||
}
|
||||
|
||||
fun ViewPager2.updatePagerHeightForChild(itemView: View) {
|
||||
itemView.post {
|
||||
val wMeasureSpec =
|
||||
View.MeasureSpec.makeMeasureSpec(itemView.width, View.MeasureSpec.EXACTLY)
|
||||
val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
itemView.measure(wMeasureSpec, hMeasureSpec)
|
||||
|
||||
if (layoutParams.height != itemView.measuredHeight) {
|
||||
layoutParams = (layoutParams)
|
||||
.also { lp ->
|
||||
// applying Fragment Root View Height to
|
||||
// the pager LayoutParams, so they match
|
||||
lp.height = itemView.measuredHeight
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
/*
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.dummy
|
||||
|
||||
object CityDataSource {
|
||||
private val BARCELONA = Pair(41.3851f, 2.1734f)
|
||||
private val BUDAPEST = Pair(47.4979f, 19.0402f)
|
||||
private val ABU_DHABI = Pair(24.4539f, 54.3773f)
|
||||
private val HYDERABAD = Pair(17.3850f, 78.4867f)
|
||||
private val QUEZON_CITY = Pair(14.6760f, 121.0437f)
|
||||
private val PARIS = Pair(48.8566f, 2.3522f)
|
||||
private val LONDON = Pair(51.5074f, 0.1278f)
|
||||
private val SHANGHAI = Pair(31.2304f, 121.4737f)
|
||||
private val MADRID = Pair(40.4168f, -3.7038f)
|
||||
private val LAHORE = Pair(31.5204f, 74.3587f)
|
||||
private val CHICAGO = Pair(41.8781f, -87.6298f)
|
||||
|
||||
val citiesLocationsList = listOf(
|
||||
BARCELONA,
|
||||
BUDAPEST,
|
||||
ABU_DHABI,
|
||||
HYDERABAD,
|
||||
QUEZON_CITY,
|
||||
PARIS,
|
||||
LONDON,
|
||||
SHANGHAI,
|
||||
MADRID,
|
||||
LAHORE,
|
||||
CHICAGO
|
||||
)
|
||||
}
|
|
@ -0,0 +1,188 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.data.repositories
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.SharedPreferencesMigration
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import foundation.e.advancedprivacy.core.utils.getValue
|
||||
import foundation.e.advancedprivacy.core.utils.mapKey
|
||||
import foundation.e.advancedprivacy.core.utils.setValue
|
||||
import foundation.e.advancedprivacy.core.utils.toggleValue
|
||||
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
class LocalStateRepositoryImpl(context: Context) : LocalStateRepository {
|
||||
companion object {
|
||||
private const val SHARED_PREFS_FILE = "localState"
|
||||
private const val PREF_DATASTORE = "localstate_datastore"
|
||||
}
|
||||
|
||||
private val blockTrackersKey = booleanPreferencesKey("blockTrackers")
|
||||
private val ipScramblingKey = booleanPreferencesKey("ipScrambling")
|
||||
private val fakeLocationKey = booleanPreferencesKey("fakeLocation")
|
||||
private val fakeLatitudeKey = floatPreferencesKey("fakeLatitude")
|
||||
private val fakeLongitudeKey = floatPreferencesKey("fakeLongitude")
|
||||
private val fakeLocationWhitelistKey = stringSetPreferencesKey("fakeLocationWhitelist")
|
||||
private val firstBootKey = booleanPreferencesKey("firstBoot")
|
||||
private val hideWarningTrackersKey = booleanPreferencesKey("hide_warning_trackers")
|
||||
private val hideWarningLocationKey = booleanPreferencesKey("hide_warning_location")
|
||||
private val hideWarningIpScramblingKey = booleanPreferencesKey("hide_warning_ipscrambling")
|
||||
private val trackersScreenLastPositionKey = intPreferencesKey("trackers_screen_last_position")
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = PREF_DATASTORE,
|
||||
produceMigrations = ::sharedPreferencesMigration
|
||||
)
|
||||
|
||||
private val store = context.dataStore
|
||||
|
||||
private fun sharedPreferencesMigration(context: Context) = listOf(SharedPreferencesMigration(context, SHARED_PREFS_FILE))
|
||||
|
||||
override val blockTrackers: Flow<Boolean> = store.mapKey(blockTrackersKey, true)
|
||||
|
||||
override suspend fun toggleBlockTrackers(enabled: Boolean?) {
|
||||
store.toggleValue(blockTrackersKey, enabled, true)
|
||||
}
|
||||
|
||||
override val areAllTrackersBlocked: MutableStateFlow<Boolean> = MutableStateFlow(false)
|
||||
|
||||
override val fakeLocationEnabled = store.mapKey(fakeLocationKey, false)
|
||||
|
||||
override suspend fun toggleFakeLocation(enabled: Boolean?) {
|
||||
store.toggleValue(fakeLocationKey, enabled, false)
|
||||
}
|
||||
|
||||
override val fakeLocation: Flow<Pair<Float, Float>> = store.data.map { preferences ->
|
||||
// Initial default value is Quezon City
|
||||
val lat = preferences[fakeLatitudeKey] ?: 14.6760f
|
||||
val lon = preferences[fakeLongitudeKey] ?: 121.0437f
|
||||
lat to lon
|
||||
}
|
||||
|
||||
override suspend fun getFakeLocation(): Pair<Float, Float> = fakeLocation.first()
|
||||
override suspend fun setFakeLocation(latLon: Pair<Float, Float>) {
|
||||
store.edit { preferences ->
|
||||
preferences[fakeLatitudeKey] = latLon.first
|
||||
preferences[fakeLongitudeKey] = latLon.second
|
||||
}
|
||||
}
|
||||
|
||||
override val fakeLocationWhitelistedApps = store.mapKey(fakeLocationWhitelistKey, emptySet())
|
||||
|
||||
override suspend fun toggleAppFakeLocationWhitelisted(app: DisplayableApp) {
|
||||
store.edit { preferences ->
|
||||
val whitelist = preferences[fakeLocationWhitelistKey] ?: emptySet()
|
||||
|
||||
val apIds = app.apps.map { it.apId }.toSet()
|
||||
|
||||
val appInWhitelist = apIds.any { whitelist.contains(it) }
|
||||
preferences[fakeLocationWhitelistKey] = if (appInWhitelist) {
|
||||
whitelist - apIds
|
||||
} else {
|
||||
whitelist + apIds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun resetFakeLocationWhitelistedApp() {
|
||||
store.setValue(fakeLocationWhitelistKey, emptySet())
|
||||
}
|
||||
|
||||
override val ipScramblingEnabled = store.mapKey(ipScramblingKey, false)
|
||||
override suspend fun toggleIpScrambling(enabled: Boolean?) {
|
||||
store.toggleValue(ipScramblingKey, enabled, false)
|
||||
}
|
||||
|
||||
override val internetPrivacyMode: MutableStateFlow<FeatureState> = MutableStateFlow(FeatureState.OFF)
|
||||
|
||||
private val _startVpnDisclaimer = MutableSharedFlow<MainFeatures>()
|
||||
|
||||
override suspend fun emitStartVpnDisclaimer(feature: MainFeatures) {
|
||||
_startVpnDisclaimer.emit(feature)
|
||||
}
|
||||
|
||||
override val startVpnDisclaimer: SharedFlow<MainFeatures> = _startVpnDisclaimer
|
||||
|
||||
private val _otherVpnRunning = MutableSharedFlow<ApplicationDescription>()
|
||||
|
||||
override suspend fun emitOtherVpnRunning(appDesc: ApplicationDescription) {
|
||||
_otherVpnRunning.emit(appDesc)
|
||||
}
|
||||
|
||||
override val otherVpnRunning: SharedFlow<ApplicationDescription> = _otherVpnRunning
|
||||
|
||||
override suspend fun isFirstBoot(): Boolean {
|
||||
return store.getValue(firstBootKey) ?: true
|
||||
}
|
||||
|
||||
override suspend fun setFirstBoot(isStillFirstBoot: Boolean) {
|
||||
store.setValue(firstBootKey, isStillFirstBoot)
|
||||
}
|
||||
|
||||
override suspend fun isHideWarningTrackers(): Boolean {
|
||||
return store.getValue(hideWarningTrackersKey) ?: false
|
||||
}
|
||||
|
||||
override suspend fun hideWarningTrackers(hide: Boolean) {
|
||||
return store.setValue(hideWarningTrackersKey, hide)
|
||||
}
|
||||
|
||||
override suspend fun isHideWarningLocation(): Boolean {
|
||||
return store.getValue(hideWarningLocationKey) ?: false
|
||||
}
|
||||
|
||||
override suspend fun hideWarningLocation(hide: Boolean) {
|
||||
return store.setValue(hideWarningLocationKey, hide)
|
||||
}
|
||||
|
||||
override suspend fun isHideWarningIpScrambling(): Boolean {
|
||||
return store.getValue(hideWarningIpScramblingKey) ?: false
|
||||
}
|
||||
|
||||
override suspend fun hideWarningIpScrambling(hide: Boolean) {
|
||||
return store.setValue(hideWarningIpScramblingKey, hide)
|
||||
}
|
||||
|
||||
override suspend fun getTrackersScreenLastPosition(): Int {
|
||||
return store.getValue(trackersScreenLastPositionKey) ?: 0
|
||||
}
|
||||
|
||||
override suspend fun setTrackersScreenLastPosition(position: Int) {
|
||||
store.setValue(trackersScreenLastPositionKey, position)
|
||||
}
|
||||
|
||||
override var trackersScreenTabStartPosition: Int = 0
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.data.repositories
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.content.res.Resources
|
||||
import androidx.annotation.StringRes
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import timber.log.Timber
|
||||
|
||||
class ResourcesRepository(private val context: Context) {
|
||||
private val defaultResources by lazy { getLocalizedResources(context, Locale("")) }
|
||||
|
||||
private fun getLocalizedResources(context: Context, desiredLocale: Locale?): Resources {
|
||||
var conf: Configuration = context.resources.configuration
|
||||
conf = Configuration(conf)
|
||||
conf.setLocale(desiredLocale)
|
||||
val localizedContext = context.createConfigurationContext(conf)
|
||||
return localizedContext.resources
|
||||
}
|
||||
|
||||
fun getFormatter(@StringRes formatRes: Int): DateTimeFormatter {
|
||||
return runCatching {
|
||||
DateTimeFormatter.ofPattern(context.getString(formatRes))
|
||||
}.getOrElse {
|
||||
Timber.w(it, "Can't parse DateTimeFormatter")
|
||||
DateTimeFormatter.ofPattern(defaultResources.getString(formatRes))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.entities
|
||||
|
||||
enum class FeatureMode {
|
||||
DENIED,
|
||||
CUSTOM,
|
||||
VULNERABLE
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.entities
|
||||
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
data class TrackersAndAppsLists(
|
||||
val trackers: List<TrackerWithCount>,
|
||||
val allApps: List<AppWithCount>,
|
||||
val appsWithTrackers: List<AppWithCount>
|
||||
)
|
||||
|
||||
data class AppWithCount(
|
||||
val app: DisplayableApp,
|
||||
val count: Int = 0
|
||||
)
|
||||
|
||||
data class TrackerWithCount(
|
||||
val tracker: Tracker,
|
||||
val count: Int = 0
|
||||
)
|
|
@ -0,0 +1,27 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.entities
|
||||
|
||||
data class TrackersPeriodicStatistics(
|
||||
val callsBlockedNLeaked: List<Pair<Int, Int>>,
|
||||
val periods: List<String>,
|
||||
val trackersCount: Int,
|
||||
val trackersAllowedCount: Int = 0,
|
||||
val graduations: List<String?>? = null
|
||||
)
|
|
@ -0,0 +1,74 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.trackers.data.StatsDatabase
|
||||
import foundation.e.advancedprivacy.trackers.data.TrackersRepository
|
||||
import foundation.e.advancedprivacy.trackers.data.WhitelistRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import foundation.e.advancedprivacy.trackers.domain.usecases.FilterHostnameUseCase
|
||||
|
||||
class AppTrackersUseCase(
|
||||
private val whitelistRepository: WhitelistRepository,
|
||||
private val trackersStateUseCase: TrackersStateUseCase,
|
||||
private val statsDatabase: StatsDatabase,
|
||||
private val trackersRepository: TrackersRepository,
|
||||
private val filterHostnameUseCase: FilterHostnameUseCase
|
||||
) {
|
||||
suspend fun toggleAppWhitelist(app: DisplayableApp, trackers: List<Tracker>, isBlocked: Boolean) {
|
||||
val realApIds = app.apps.map { it.apId }
|
||||
val trackerIds = trackers.map { it.id }
|
||||
|
||||
whitelistRepository.setWhiteListed(realApIds, !isBlocked)
|
||||
whitelistRepository.setWhitelistedTrackersForApps(realApIds, trackerIds, !isBlocked)
|
||||
trackersStateUseCase.updateAllTrackersBlockedState()
|
||||
}
|
||||
|
||||
suspend fun clearWhitelist(app: DisplayableApp) {
|
||||
app.apps.forEach {
|
||||
whitelistRepository.clearWhiteList(it.apId)
|
||||
}
|
||||
trackersStateUseCase.updateAllTrackersBlockedState()
|
||||
}
|
||||
|
||||
suspend fun getCalls(app: DisplayableApp): Pair<Int, Int> {
|
||||
return app.apps.map {
|
||||
statsDatabase.getCallsForApp(it.apId)
|
||||
}.unzip().let { (blocked, leaked) ->
|
||||
blocked.sum() to leaked.sum()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getTrackersWithBlockedList(app: DisplayableApp): List<Pair<Tracker, Boolean>> {
|
||||
val realApIds = app.apps.map { it.apId }
|
||||
val trackers = statsDatabase.getTrackerIds(realApIds)
|
||||
.mapNotNull { trackersRepository.getTracker(it) }
|
||||
|
||||
return enrichWithBlockedState(app, trackers)
|
||||
}
|
||||
|
||||
suspend fun enrichWithBlockedState(app: DisplayableApp, trackers: List<Tracker>): List<Pair<Tracker, Boolean>> {
|
||||
val realAppUids = app.apps.map { it.uid }
|
||||
return trackers.map { tracker ->
|
||||
tracker to !realAppUids.any { uid ->
|
||||
filterHostnameUseCase.isWhitelisted(uid, tracker.id)
|
||||
}
|
||||
}.sortedBy { it.first.label.lowercase() }
|
||||
}
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
class FakeLocationForAppUseCase(
|
||||
private val appListRepository: AppListRepository,
|
||||
localStateRepository: LocalStateRepository,
|
||||
backgroundScope: CoroutineScope
|
||||
) {
|
||||
// Cache these values to allow true sync exectution on getFakeLocationOrNull,
|
||||
// which is called by the ContentProvider
|
||||
private var fakeLocation: Pair<Float, Float>? = null
|
||||
private var whitelistedApp: Set<String> = emptySet()
|
||||
|
||||
private val nullFakeLocationPkgs = listOf(
|
||||
AppListRepository.PNAME_MICROG_SERVICES_CORE,
|
||||
AppListRepository.PNAME_FUSED_LOCATION,
|
||||
AppListRepository.PNAME_ANDROID_SYSTEM
|
||||
)
|
||||
|
||||
init {
|
||||
combine(
|
||||
localStateRepository.fakeLocationEnabled,
|
||||
localStateRepository.fakeLocation
|
||||
) { enabled, latLon ->
|
||||
fakeLocation = if (enabled) latLon else null
|
||||
}.launchIn(backgroundScope)
|
||||
|
||||
localStateRepository.fakeLocationWhitelistedApps.map { whitelistedApp = it }.launchIn(backgroundScope)
|
||||
}
|
||||
|
||||
fun getFakeLocationOrNull(packageName: String?, uid: Int): Pair<Float, Float>? {
|
||||
if (packageName == null || fakeLocation == null || packageName in nullFakeLocationPkgs) {
|
||||
return null
|
||||
}
|
||||
|
||||
val app = appListRepository.getApp(uid)
|
||||
return if (app?.apId != null && app.apId in whitelistedApp) {
|
||||
null
|
||||
} else {
|
||||
fakeLocation
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.LocationMode
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import foundation.e.advancedprivacy.dummy.CityDataSource
|
||||
import kotlin.random.Random
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class FakeLocationStateUseCase(
|
||||
private val localStateRepository: LocalStateRepository,
|
||||
private val citiesRepository: CityDataSource,
|
||||
private val appListRepository: AppListRepository,
|
||||
coroutineScope: CoroutineScope
|
||||
) {
|
||||
private val _configuredLocationMode = MutableStateFlow<Triple<LocationMode, Float?, Float?>>(
|
||||
Triple(LocationMode.REAL_LOCATION, null, null)
|
||||
)
|
||||
val configuredLocationMode: StateFlow<Triple<LocationMode, Float?, Float?>> = _configuredLocationMode
|
||||
|
||||
init {
|
||||
coroutineScope.launch {
|
||||
localStateRepository.fakeLocationEnabled.collect {
|
||||
applySettings(it, localStateRepository.getFakeLocation())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun applySettings(isEnabled: Boolean, fakeLocation: Pair<Float, Float>, isSpecificLocation: Boolean = false) {
|
||||
val locationMode = when {
|
||||
!isEnabled -> LocationMode.REAL_LOCATION
|
||||
isRandomLocation(fakeLocation, isSpecificLocation) -> LocationMode.RANDOM_LOCATION
|
||||
else -> LocationMode.SPECIFIC_LOCATION
|
||||
}
|
||||
|
||||
_configuredLocationMode.value = Triple(locationMode, fakeLocation.first, fakeLocation.second)
|
||||
}
|
||||
|
||||
private fun isRandomLocation(fakeLocation: Pair<Float, Float>, isSpecificLocation: Boolean): Boolean {
|
||||
return fakeLocation in citiesRepository.citiesLocationsList && !isSpecificLocation
|
||||
}
|
||||
|
||||
suspend fun setSpecificLocation(latitude: Float, longitude: Float) {
|
||||
setFakeLocation(latitude to longitude, true)
|
||||
}
|
||||
|
||||
suspend fun setRandomLocation() {
|
||||
val randomIndex = Random.nextInt(citiesRepository.citiesLocationsList.size)
|
||||
val location = citiesRepository.citiesLocationsList[randomIndex]
|
||||
|
||||
setFakeLocation(location)
|
||||
}
|
||||
|
||||
private suspend fun setFakeLocation(location: Pair<Float, Float>, isSpecificLocation: Boolean = false) {
|
||||
localStateRepository.setFakeLocation(location)
|
||||
localStateRepository.toggleFakeLocation(true)
|
||||
applySettings(true, location, isSpecificLocation)
|
||||
}
|
||||
|
||||
suspend fun stopFakeLocation() {
|
||||
localStateRepository.toggleFakeLocation(false)
|
||||
applySettings(false, localStateRepository.getFakeLocation())
|
||||
}
|
||||
|
||||
suspend fun toggleBlacklist(app: DisplayableApp) {
|
||||
localStateRepository.toggleAppFakeLocationWhitelisted(app)
|
||||
}
|
||||
|
||||
suspend fun resetBlacklist() {
|
||||
localStateRepository.resetFakeLocationWhitelistedApp()
|
||||
}
|
||||
|
||||
fun canResetBlacklist(): Flow<Boolean> = localStateRepository.fakeLocationWhitelistedApps.map {
|
||||
it.isNotEmpty()
|
||||
}
|
||||
|
||||
fun appsWithBlacklist(): Flow<List<ToggleableApp>> {
|
||||
return combine(
|
||||
appListRepository.displayableApps.map { apps ->
|
||||
apps.filter { it.hasLocationPermission }.sortedBy { it.label.toString() }
|
||||
},
|
||||
localStateRepository.fakeLocationWhitelistedApps
|
||||
) { apps, whitelist ->
|
||||
apps.map { app ->
|
||||
ToggleableApp(app = app, isOn = !app.apps.any { whitelist.contains(it.apId) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,70 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
|
||||
class GetQuickPrivacyStateUseCase(
|
||||
private val localStateRepository: LocalStateRepository
|
||||
) {
|
||||
val trackerMode: Flow<FeatureMode> = combine(
|
||||
localStateRepository.blockTrackers,
|
||||
localStateRepository.areAllTrackersBlocked
|
||||
) { isBlockTrackers, isAllTrackersBlocked ->
|
||||
when {
|
||||
isBlockTrackers && isAllTrackersBlocked -> FeatureMode.DENIED
|
||||
isBlockTrackers && !isAllTrackersBlocked -> FeatureMode.CUSTOM
|
||||
else -> FeatureMode.VULNERABLE
|
||||
}
|
||||
}
|
||||
|
||||
val locationMode: Flow<FeatureMode> = combine(
|
||||
localStateRepository.fakeLocationEnabled,
|
||||
localStateRepository.fakeLocationWhitelistedApps
|
||||
) { enabled, whitelist ->
|
||||
when {
|
||||
!enabled -> FeatureMode.VULNERABLE
|
||||
whitelist.isEmpty() -> FeatureMode.DENIED
|
||||
else -> FeatureMode.CUSTOM
|
||||
}
|
||||
}
|
||||
|
||||
val ipScramblingMode: Flow<FeatureState> =
|
||||
localStateRepository.internetPrivacyMode
|
||||
|
||||
suspend fun toggleTrackers(enabled: Boolean?) {
|
||||
localStateRepository.toggleBlockTrackers(enabled)
|
||||
}
|
||||
|
||||
suspend fun toggleLocation(enabled: Boolean?) {
|
||||
localStateRepository.toggleFakeLocation(enabled)
|
||||
}
|
||||
|
||||
suspend fun toggleIpScrambling(enabled: Boolean?) {
|
||||
localStateRepository.toggleIpScrambling(enabled)
|
||||
}
|
||||
|
||||
val otherVpnRunning: SharedFlow<ApplicationDescription> = localStateRepository.otherVpnRunning
|
||||
}
|
|
@ -0,0 +1,102 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.entities.ProfileType
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import foundation.e.advancedprivacy.ipscrambler.OrbotSupervisor
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
class IpScramblingStateUseCase(
|
||||
private val orbotSupervisor: OrbotSupervisor,
|
||||
private val localStateRepository: LocalStateRepository,
|
||||
private val appListRepository: AppListRepository,
|
||||
private val backgroundScope: CoroutineScope
|
||||
) {
|
||||
val internetPrivacyMode: StateFlow<FeatureState> = orbotSupervisor.state
|
||||
|
||||
private val whitelistedPackages = MutableStateFlow(orbotSupervisor.appList)
|
||||
|
||||
init {
|
||||
orbotSupervisor.requestStatus()
|
||||
|
||||
orbotSupervisor.state.map {
|
||||
localStateRepository.internetPrivacyMode.value = it
|
||||
}.launchIn(backgroundScope)
|
||||
|
||||
whitelistedPackages.map {
|
||||
orbotSupervisor.appList = it
|
||||
}.launchIn(backgroundScope)
|
||||
}
|
||||
|
||||
suspend fun toggle(hideIp: Boolean) {
|
||||
localStateRepository.toggleIpScrambling(enabled = hideIp)
|
||||
}
|
||||
|
||||
suspend fun getTorToggleableApp(): Flow<List<ToggleableApp>> {
|
||||
return combine(
|
||||
appListRepository.displayableApps.map { apps ->
|
||||
apps.filter { app ->
|
||||
app.hasInternetPermission && app.profileType == ProfileType.MAIN
|
||||
}
|
||||
},
|
||||
whitelistedPackages
|
||||
) { apps, pNames ->
|
||||
apps.map { app ->
|
||||
ToggleableApp(app = app, isOn = !app.isWhitelisted(pNames))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleBypassTor(app: DisplayableApp) {
|
||||
whitelistedPackages.update { whitelist ->
|
||||
val packageNames = app.apps.map { it.packageName }.toSet()
|
||||
if (app.isWhitelisted()) {
|
||||
whitelist.minus(packageNames)
|
||||
} else {
|
||||
whitelist.union(packageNames)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val availablesLocations: List<String> = orbotSupervisor.getAvailablesLocations().sorted()
|
||||
|
||||
val exitCountry: String get() = orbotSupervisor.getExitCountryCode()
|
||||
|
||||
suspend fun setExitCountry(locationId: String) {
|
||||
if (locationId != exitCountry) {
|
||||
orbotSupervisor.setExitCountryCode(locationId)
|
||||
}
|
||||
}
|
||||
|
||||
private fun DisplayableApp.isWhitelisted(whitelistedPackageNames: Set<String> = whitelistedPackages.value): Boolean = apps.any {
|
||||
it.packageName in whitelistedPackageNames
|
||||
}
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.location.Location
|
||||
import android.location.LocationListener
|
||||
import android.location.LocationManager
|
||||
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
|
||||
import foundation.e.advancedprivacy.externalinterfaces.permissions.IPermissionsPrivacyModule
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import timber.log.Timber
|
||||
|
||||
class ListenLocationUseCase(
|
||||
private val permissionsModule: IPermissionsPrivacyModule,
|
||||
private val appContext: Context,
|
||||
private val appDesc: ApplicationDescription
|
||||
) {
|
||||
companion object {
|
||||
const val MIN_TIME_INTERVAL = 1000L
|
||||
const val MIN_DIST_INTERVAL = 0f
|
||||
}
|
||||
|
||||
private val locationManager: LocationManager
|
||||
get() = appContext.getSystemService(LocationManager::class.java) as LocationManager
|
||||
|
||||
private fun hasAcquireLocationPermission(): Boolean {
|
||||
return isAccessFineLocationGranted() ||
|
||||
permissionsModule.toggleDangerousPermission(appDesc, android.Manifest.permission.ACCESS_FINE_LOCATION, true)
|
||||
}
|
||||
|
||||
private fun isAccessFineLocationGranted(): Boolean {
|
||||
return appContext.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
private val _currentLocation = MutableStateFlow<Location?>(null)
|
||||
val currentLocation: StateFlow<Location?> = _currentLocation
|
||||
|
||||
private var localListener = object : LocationListener {
|
||||
|
||||
override fun onLocationChanged(location: Location) {
|
||||
_currentLocation.update { location }
|
||||
}
|
||||
|
||||
override fun onProviderEnabled(provider: String) {
|
||||
reset()
|
||||
}
|
||||
|
||||
override fun onProviderDisabled(provider: String) {
|
||||
reset()
|
||||
}
|
||||
|
||||
private fun reset() {
|
||||
stopListeningLocation()
|
||||
_currentLocation.value = null
|
||||
startListeningLocation()
|
||||
}
|
||||
}
|
||||
|
||||
fun startListeningLocation(): Boolean {
|
||||
return if (hasAcquireLocationPermission()) {
|
||||
requestLocationUpdates()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun stopListeningLocation() {
|
||||
locationManager.removeUpdates(localListener)
|
||||
}
|
||||
|
||||
private fun requestLocationUpdates() {
|
||||
val networkProvider = LocationManager.NETWORK_PROVIDER
|
||||
.takeIf { it in locationManager.allProviders }
|
||||
val gpsProvider = LocationManager.GPS_PROVIDER
|
||||
.takeIf { it in locationManager.allProviders }
|
||||
|
||||
try {
|
||||
networkProvider?.let {
|
||||
locationManager.requestLocationUpdates(
|
||||
it,
|
||||
MIN_TIME_INTERVAL,
|
||||
MIN_DIST_INTERVAL,
|
||||
localListener
|
||||
)
|
||||
}
|
||||
gpsProvider?.let {
|
||||
locationManager.requestLocationUpdates(
|
||||
it,
|
||||
MIN_TIME_INTERVAL,
|
||||
MIN_DIST_INTERVAL,
|
||||
localListener
|
||||
)
|
||||
}
|
||||
|
||||
var lastKnownLocation = networkProvider?.let {
|
||||
locationManager.getLastKnownLocation(it)
|
||||
}
|
||||
|
||||
if (lastKnownLocation == null) {
|
||||
lastKnownLocation = gpsProvider?.let {
|
||||
locationManager.getLastKnownLocation(it)
|
||||
}
|
||||
}
|
||||
|
||||
lastKnownLocation?.let { localListener.onLocationChanged(it) }
|
||||
} catch (se: SecurityException) {
|
||||
Timber.e(se, "Missing permission")
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.FakeLocation
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.IpScrambling
|
||||
import foundation.e.advancedprivacy.domain.entities.MainFeatures.TrackersControl
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
|
||||
class ShowFeaturesWarningUseCase(
|
||||
private val localStateRepository: LocalStateRepository
|
||||
) {
|
||||
|
||||
fun showWarning(): Flow<MainFeatures> {
|
||||
return merge(
|
||||
localStateRepository.fakeLocationEnabled.drop(1).filter { it }
|
||||
.filter { it && !localStateRepository.isHideWarningLocation() }
|
||||
.map { FakeLocation },
|
||||
localStateRepository.startVpnDisclaimer.filter {
|
||||
(it is IpScrambling && !localStateRepository.isHideWarningIpScrambling()) ||
|
||||
(it is TrackersControl && !localStateRepository.isHideWarningTrackers())
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun doNotShowAgain(feature: MainFeatures) {
|
||||
when (feature) {
|
||||
is TrackersControl -> localStateRepository.hideWarningTrackers(true)
|
||||
is FakeLocation -> localStateRepository.hideWarningLocation(true)
|
||||
is IpScrambling -> localStateRepository.hideWarningIpScrambling(true)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
import foundation.e.advancedprivacy.trackers.data.StatsDatabase
|
||||
import foundation.e.advancedprivacy.trackers.data.WhitelistRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import foundation.e.advancedprivacy.trackers.domain.usecases.FilterHostnameUseCase
|
||||
|
||||
class TrackerDetailsUseCase(
|
||||
private val whitelistRepository: WhitelistRepository,
|
||||
private val trackersStateUseCase: TrackersStateUseCase,
|
||||
private val appListRepository: AppListRepository,
|
||||
private val statsDatabase: StatsDatabase,
|
||||
private val filterHostnameUseCase: FilterHostnameUseCase
|
||||
) {
|
||||
suspend fun toggleTrackerWhitelist(tracker: Tracker, apps: List<DisplayableApp>, isBlocked: Boolean) {
|
||||
whitelistRepository.setWhiteListed(tracker, !isBlocked)
|
||||
whitelistRepository.setWhitelistedAppsForTracker(
|
||||
apps.flatMap { it.apps }.map { it.apId },
|
||||
tracker.id,
|
||||
!isBlocked
|
||||
)
|
||||
trackersStateUseCase.updateAllTrackersBlockedState()
|
||||
}
|
||||
|
||||
suspend fun getAppsWithBlockedState(tracker: Tracker): List<ToggleableApp> {
|
||||
return enrichWithBlockedState(
|
||||
statsDatabase.getApIds(tracker.id).mapNotNull {
|
||||
appListRepository.getInternetAppByApId(it)
|
||||
}.distinct().sortedBy { it.label.toString() },
|
||||
tracker
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun enrichWithBlockedState(apps: List<DisplayableApp>, tracker: Tracker): List<ToggleableApp> {
|
||||
return apps.map { app ->
|
||||
ToggleableApp(
|
||||
app = app,
|
||||
isOn = app.apps.any { !filterHostnameUseCase.isWhitelisted(it.uid, tracker.id) }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getCalls(tracker: Tracker): Pair<Int, Int> {
|
||||
return statsDatabase.getCallsForTracker(tracker.id)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,134 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.AppWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackerWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackersAndAppsLists
|
||||
import foundation.e.advancedprivacy.features.trackers.Period
|
||||
import foundation.e.advancedprivacy.trackers.data.StatsDatabase
|
||||
import foundation.e.advancedprivacy.trackers.data.TrackersRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import java.time.Instant
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
class TrackersAndAppsListsUseCase(
|
||||
private val statsDatabase: StatsDatabase,
|
||||
private val trackersRepository: TrackersRepository,
|
||||
private val appListRepository: AppListRepository
|
||||
) {
|
||||
suspend fun getAppsAndTrackersCounts(period: Period): TrackersAndAppsLists {
|
||||
val countByEntitiesMaps = getCountByEntityMaps(period)
|
||||
|
||||
return TrackersAndAppsLists(
|
||||
trackers = buildTrackerList(countByEntitiesMaps.countByTrackers),
|
||||
allApps = buildAllAppList(countByEntitiesMaps.countByApps),
|
||||
appsWithTrackers = buildAppList(countByEntitiesMaps.countByApps)
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun buildWallOfShame(): TrackersAndAppsLists {
|
||||
val trackers = statsDatabase
|
||||
.get5MostCalledTrackers(since = Period.MONTH.getPeriodStart().epochSecond)
|
||||
.mapNotNull { (trackerId, calls) ->
|
||||
trackersRepository.getTracker(trackerId)?.let {
|
||||
TrackerWithCount(it, calls)
|
||||
}
|
||||
}
|
||||
|
||||
return TrackersAndAppsLists(
|
||||
trackers = trackers,
|
||||
appsWithTrackers = get5MostTrackedAppsLastMonth(),
|
||||
allApps = emptyList()
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun get5MostTrackedAppsLastMonth(): List<AppWithCount> {
|
||||
val countByApIds = statsDatabase.getCallsByAppIds(since = Period.MONTH.getPeriodStart().epochSecond)
|
||||
|
||||
val countByApps = mutableMapOf<DisplayableApp, Int>()
|
||||
countByApIds.forEach { (apId, count) ->
|
||||
appListRepository.getInternetAppByApId(apId)?.let { app ->
|
||||
countByApps[app] = count + (countByApps[app] ?: 0)
|
||||
}
|
||||
}
|
||||
return countByApps.toList().sortedByDescending { it.second }.take(5).map { (app, count) ->
|
||||
AppWithCount(app, count)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun getCountByEntityMaps(period: Period): CountByEntitiesMaps {
|
||||
val periodStart: Instant = period.getPeriodStart()
|
||||
val trackersAndAppsIds = statsDatabase.getDistinctTrackerAndApp(periodStart)
|
||||
val trackersAndApps = mapIdsToEntities(trackersAndAppsIds)
|
||||
return foldToCountByEntityMaps(trackersAndApps)
|
||||
}
|
||||
|
||||
private fun buildTrackerList(countByTracker: Map<Tracker, Int>): List<TrackerWithCount> {
|
||||
return countByTracker.map { (tracker, count) ->
|
||||
TrackerWithCount(tracker = tracker, count = count)
|
||||
}.sortedByDescending { it.count }
|
||||
}
|
||||
|
||||
private suspend fun buildAllAppList(countByApp: Map<DisplayableApp, Int>): List<AppWithCount> {
|
||||
return appListRepository.displayableApps.first()
|
||||
.filter { it.hasInternetPermission }
|
||||
.map { app: DisplayableApp ->
|
||||
AppWithCount(app = app, count = countByApp[app] ?: 0)
|
||||
}.sortedByDescending { it.count }
|
||||
}
|
||||
|
||||
private fun buildAppList(countByApp: Map<DisplayableApp, Int>): List<AppWithCount> {
|
||||
return countByApp.map { (app, count) ->
|
||||
AppWithCount(app = app, count = count)
|
||||
}.sortedByDescending { it.count }
|
||||
}
|
||||
|
||||
private suspend fun mapIdsToEntities(trackersAndAppsIds: List<Pair<String, String>>): List<Pair<Tracker, DisplayableApp>> {
|
||||
return trackersAndAppsIds.mapNotNull { (trackerId, apId) ->
|
||||
trackersRepository.getTracker(trackerId)?.let { tracker ->
|
||||
appListRepository.getInternetAppByApId(apId)?.let { app ->
|
||||
tracker to app
|
||||
}
|
||||
}
|
||||
// appListsRepository.getDisplayableApp() may transform many apId to one
|
||||
// ApplicationDescription, so the lists is not distinct anymore.
|
||||
}.distinct()
|
||||
}
|
||||
|
||||
private fun foldToCountByEntityMaps(trackersAndApps: List<Pair<Tracker, DisplayableApp>>): CountByEntitiesMaps {
|
||||
return trackersAndApps.fold(
|
||||
mutableMapOf<DisplayableApp, Int>() to mutableMapOf<Tracker, Int>()
|
||||
) { (countByApp, countByTracker), (tracker, app) ->
|
||||
countByApp[app] = countByApp.getOrDefault(app, 0) + 1
|
||||
countByTracker[tracker] = countByTracker.getOrDefault(tracker, 0) + 1
|
||||
countByApp to countByTracker
|
||||
}.let { (countByApp, countByTracker) ->
|
||||
CountByEntitiesMaps(
|
||||
countByApps = countByApp,
|
||||
countByTrackers = countByTracker
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private data class CountByEntitiesMaps(
|
||||
val countByApps: Map<DisplayableApp, Int>,
|
||||
val countByTrackers: Map<Tracker, Int>
|
||||
)
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class TrackersScreenUseCase(
|
||||
private val localStateRepository: LocalStateRepository,
|
||||
private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO
|
||||
) {
|
||||
|
||||
suspend fun getLastPosition(): Int = withContext(backgroundDispatcher) {
|
||||
localStateRepository.getTrackersScreenLastPosition()
|
||||
}
|
||||
|
||||
suspend fun savePosition(currentPosition: Int) = withContext(backgroundDispatcher) {
|
||||
localStateRepository.setTrackersScreenLastPosition(currentPosition)
|
||||
}
|
||||
|
||||
fun getTrackerTabStartPosition(): Int {
|
||||
return localStateRepository.trackersScreenTabStartPosition
|
||||
}
|
||||
|
||||
fun resetTrackerTabStartPosition() {
|
||||
localStateRepository.trackersScreenTabStartPosition = -1
|
||||
}
|
||||
|
||||
suspend fun preselectTab(periodPosition: Int, tabPosition: Int) = withContext(backgroundDispatcher) {
|
||||
localStateRepository.setTrackersScreenLastPosition(periodPosition)
|
||||
localStateRepository.trackersScreenTabStartPosition = tabPosition
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.repositories.LocalStateRepository
|
||||
import foundation.e.advancedprivacy.trackers.data.WhitelistRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class TrackersStateUseCase(
|
||||
private val whitelistRepository: WhitelistRepository,
|
||||
private val localStateRepository: LocalStateRepository,
|
||||
coroutineScope: CoroutineScope
|
||||
) {
|
||||
init {
|
||||
coroutineScope.launch {
|
||||
localStateRepository.blockTrackers.collect { enabled ->
|
||||
whitelistRepository.isBlockingEnabled = enabled
|
||||
updateAllTrackersBlockedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateAllTrackersBlockedState() {
|
||||
localStateRepository.areAllTrackersBlocked.value = whitelistRepository.isBlockingEnabled &&
|
||||
whitelistRepository.areWhiteListEmpty()
|
||||
}
|
||||
|
||||
fun isWhitelisted(app: DisplayableApp): Boolean {
|
||||
return isWhitelisted(app, whitelistRepository)
|
||||
}
|
||||
|
||||
fun isWhitelisted(tracker: Tracker): Boolean {
|
||||
return whitelistRepository.isWhiteListed(tracker)
|
||||
}
|
||||
|
||||
suspend fun blockTracker(app: DisplayableApp, tracker: Tracker, isBlocked: Boolean) {
|
||||
whitelistRepository.setWhitelistedAppsForTracker(
|
||||
app.apps.map { it.apId },
|
||||
tracker.id,
|
||||
!isBlocked
|
||||
)
|
||||
updateAllTrackersBlockedState()
|
||||
}
|
||||
}
|
||||
|
||||
fun isWhitelisted(app: DisplayableApp, whitelistRepository: WhitelistRepository): Boolean {
|
||||
return app.apps.any(whitelistRepository::isAppWhiteListed)
|
||||
}
|
|
@ -0,0 +1,184 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.domain.usecases
|
||||
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.throttleFirst
|
||||
import foundation.e.advancedprivacy.data.repositories.AppListRepository
|
||||
import foundation.e.advancedprivacy.data.repositories.ResourcesRepository
|
||||
import foundation.e.advancedprivacy.domain.entities.ApplicationDescription
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackersPeriodicStatistics
|
||||
import foundation.e.advancedprivacy.features.trackers.Period
|
||||
import foundation.e.advancedprivacy.trackers.data.StatsDatabase
|
||||
import foundation.e.advancedprivacy.trackers.data.TrackersRepository
|
||||
import foundation.e.advancedprivacy.trackers.data.WhitelistRepository
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import java.time.ZonedDateTime
|
||||
import java.time.temporal.ChronoUnit
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
|
||||
class TrackersStatisticsUseCase(
|
||||
private val whitelistRepository: WhitelistRepository,
|
||||
private val trackersRepository: TrackersRepository,
|
||||
private val appListRepository: AppListRepository,
|
||||
private val statsDatabase: StatsDatabase,
|
||||
private val resourcesRepository: ResourcesRepository
|
||||
) {
|
||||
fun initAppList() {
|
||||
appListRepository.refreshAppDescriptions()
|
||||
}
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
fun listenUpdates(debounce: Duration = 1.seconds) = statsDatabase.newDataAvailable
|
||||
.throttleFirst(windowDuration = debounce)
|
||||
.onStart { emit(Unit) }
|
||||
|
||||
private fun buildGraduations(period: Period): List<String?> {
|
||||
return when (period) {
|
||||
Period.DAY -> buildDayGraduations()
|
||||
Period.MONTH -> buildMonthGraduations()
|
||||
Period.YEAR -> buildYearGraduations()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildDayGraduations(): List<String?> {
|
||||
val formatter = resourcesRepository.getFormatter(R.string.trackers_graph_hours_period_format)
|
||||
|
||||
val periods = mutableListOf<String?>()
|
||||
var end = ZonedDateTime.now()
|
||||
for (i in 1..24) {
|
||||
val start = end.truncatedTo(ChronoUnit.HOURS)
|
||||
periods.add(if (start.hour % 6 == 0) formatter.format(start) else null)
|
||||
end = start.minus(1, ChronoUnit.MINUTES)
|
||||
}
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
private fun buildMonthGraduations(): List<String?> {
|
||||
val formatter = resourcesRepository.getFormatter(
|
||||
R.string.trackers_graph_month_graduations_format
|
||||
)
|
||||
|
||||
val periods = mutableListOf<String?>()
|
||||
var end = ZonedDateTime.now()
|
||||
for (i in 1..30) {
|
||||
val start = end.truncatedTo(ChronoUnit.DAYS)
|
||||
periods.add(if ((start.dayOfMonth) % 6 == 0) formatter.format(start) else null)
|
||||
end = start.minus(1, ChronoUnit.HOURS)
|
||||
}
|
||||
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
private fun buildYearGraduations(): List<String?> {
|
||||
val formatter = resourcesRepository.getFormatter(R.string.trackers_graph_year_graduations_format)
|
||||
|
||||
val periods = mutableListOf<String?>()
|
||||
var end = ZonedDateTime.now()
|
||||
for (i in 1..12) {
|
||||
val start = end.truncatedTo(ChronoUnit.DAYS).let {
|
||||
it.minusDays(it.dayOfMonth.toLong())
|
||||
}
|
||||
periods.add(if (start.monthValue % 3 == 0) formatter.format(start) else null)
|
||||
end = start.minus(1, ChronoUnit.DAYS)
|
||||
}
|
||||
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
private fun buildLabels(period: Period): List<String> {
|
||||
return when (period) {
|
||||
Period.DAY -> buildDayLabels()
|
||||
Period.MONTH -> buildMonthLabels()
|
||||
Period.YEAR -> buildYearLabels()
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildDayLabels(): List<String> {
|
||||
val formatter = resourcesRepository.getFormatter(R.string.trackers_graph_hours_period_format)
|
||||
|
||||
val periods = mutableListOf<String>()
|
||||
var end = ZonedDateTime.now()
|
||||
for (i in 1..24) {
|
||||
val start = end.truncatedTo(ChronoUnit.HOURS)
|
||||
periods.add("${formatter.format(start)} - ${formatter.format(end)}")
|
||||
end = start.minus(1, ChronoUnit.MINUTES)
|
||||
}
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
private fun buildMonthLabels(): List<String> {
|
||||
val formater = resourcesRepository.getFormatter(R.string.trackers_graph_days_period_format)
|
||||
|
||||
val periods = mutableListOf<String>()
|
||||
var day = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS)
|
||||
for (i in 1..30) {
|
||||
periods.add(formater.format(day))
|
||||
day = day.minus(1, ChronoUnit.DAYS)
|
||||
}
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
private fun buildYearLabels(): List<String> {
|
||||
val formater = resourcesRepository.getFormatter(R.string.trackers_graph_months_period_format)
|
||||
|
||||
val periods = mutableListOf<String>()
|
||||
var month = ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1)
|
||||
for (i in 1..12) {
|
||||
periods.add(formater.format(month))
|
||||
month = month.minus(1, ChronoUnit.MONTHS)
|
||||
}
|
||||
return periods.reversed()
|
||||
}
|
||||
|
||||
suspend fun getGraphData(period: Period): TrackersPeriodicStatistics {
|
||||
return TrackersPeriodicStatistics(
|
||||
callsBlockedNLeaked = statsDatabase.getTrackersCallsOnPeriod(
|
||||
period.periodsCount,
|
||||
period.periodUnit
|
||||
),
|
||||
periods = buildLabels(period),
|
||||
trackersCount = statsDatabase.getTrackersCount(period.periodsCount, period.periodUnit),
|
||||
trackersAllowedCount = statsDatabase.getLeakedTrackersCount(period.periodsCount, period.periodUnit),
|
||||
graduations = buildGraduations(period)
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun isWhiteListEmpty(app: DisplayableApp): Boolean {
|
||||
return app.apps.all { getWhiteList(it).isEmpty() }
|
||||
}
|
||||
|
||||
suspend fun getLastMonthBlockedLeaksCount(): Int {
|
||||
return statsDatabase.getBlockedLeaksCount(Period.MONTH.periodsCount, Period.MONTH.periodUnit)
|
||||
}
|
||||
|
||||
suspend fun getLastMonthAppsWithBlockedLeaksCount(): Int {
|
||||
return statsDatabase.getAppsWithBlockedLeaksCount(Period.MONTH.periodsCount, Period.MONTH.periodUnit)
|
||||
}
|
||||
|
||||
private fun getWhiteList(app: ApplicationDescription): List<Tracker> {
|
||||
return whitelistRepository.getWhiteListForApp(app).mapNotNull {
|
||||
trackersRepository.getTracker(it)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.externalinterfaces.contentproviders
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import foundation.e.advancedprivacy.domain.usecases.FakeLocationForAppUseCase
|
||||
import org.koin.android.ext.android.inject
|
||||
|
||||
class FakeLocationContentProvider : ContentProvider() {
|
||||
private val PARAM_UID = "uid"
|
||||
private val PARAM_LATITUDE = "latitude"
|
||||
private val PARAM_LONGITUDE = "longitude"
|
||||
|
||||
private val fakeLocationForAppUseCase: FakeLocationForAppUseCase by inject()
|
||||
|
||||
override fun call(method: String, arg: String?, extras: Bundle?): Bundle? {
|
||||
val appUid = extras?.getInt(PARAM_UID, -1) ?: -1
|
||||
|
||||
return fakeLocationForAppUseCase.getFakeLocationOrNull(arg, appUid)?.let { (lat, lon) ->
|
||||
Bundle().apply {
|
||||
putDouble(PARAM_LATITUDE, lat.toDouble())
|
||||
putDouble(PARAM_LONGITUDE, lon.toDouble())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
override fun query(
|
||||
uri: Uri,
|
||||
projection: Array<out String>?,
|
||||
selection: String?,
|
||||
selectionArgs: Array<out String>?,
|
||||
sortOrder: String?
|
||||
): Cursor? {
|
||||
// Use call instead
|
||||
return null
|
||||
}
|
||||
|
||||
override fun getType(uri: Uri): String? {
|
||||
return "text/plain"
|
||||
}
|
||||
|
||||
override fun insert(p0: Uri, p1: ContentValues?): Uri? {
|
||||
// ReadOnly content provider
|
||||
return null
|
||||
}
|
||||
|
||||
override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int {
|
||||
// ReadOnly content provider
|
||||
return 0
|
||||
}
|
||||
|
||||
override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int {
|
||||
// ReadOnly content provider
|
||||
return 0
|
||||
}
|
||||
}
|
|
@ -0,0 +1,252 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.dashboard
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.content.ContextCompat.getColor
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import com.google.android.material.tabs.TabLayoutMediator
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.BigNumberFormatter
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.databinding.FragmentDashboardBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.features.dashboard.DashboardViewModel.SingleEvent
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackerTab
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
|
||||
class DashboardFragment : NavToolbarFragment(R.layout.fragment_dashboard) {
|
||||
private val viewModel: DashboardViewModel by viewModel()
|
||||
private val numberFormatter: BigNumberFormatter by lazy { BigNumberFormatter(requireContext()) }
|
||||
|
||||
private lateinit var binding: FragmentDashboardBinding
|
||||
|
||||
private lateinit var tabAdapter: ShameListsTabPagerAdapter
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
binding = FragmentDashboardBinding.bind(view)
|
||||
|
||||
with(binding.dataBlockedTrackers) {
|
||||
primaryMessage.apply {
|
||||
setText(R.string.dashboard_data_blocked_trackers_primary)
|
||||
setCompoundDrawables(
|
||||
ContextCompat.getDrawable(requireContext(), R.drawable.ic_block_24),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
secondaryMessage.setText(R.string.dashboard_data_blocked_trackers_secondary)
|
||||
}
|
||||
with(binding.dataApps) {
|
||||
primaryMessage.apply {
|
||||
setText(R.string.dashboard_data_apps_primary)
|
||||
setCompoundDrawables(
|
||||
ContextCompat.getDrawable(requireContext(), R.drawable.ic_apps_24),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
secondaryMessage.setText(R.string.dashboard_data_apps_secondary)
|
||||
}
|
||||
|
||||
binding.trackersControl.title.setText(R.string.dashboard_trackers_title)
|
||||
binding.fakeLocation.title.setText(R.string.dashboard_location_title)
|
||||
binding.ipScrambling.title.setText(R.string.dashboard_ipscrambling_title)
|
||||
|
||||
tabAdapter = ShameListsTabPagerAdapter(
|
||||
onClickShameApp = viewModel::onClickShameApp,
|
||||
onClickShameTracker = viewModel::onClickShameTracker,
|
||||
onClickViewAllApps = viewModel::onClickViewAllApps,
|
||||
onClickViewAllTrackers = viewModel::onClickViewAllTrackers
|
||||
)
|
||||
|
||||
binding.listsPager.adapter = tabAdapter
|
||||
|
||||
TabLayoutMediator(binding.listsTabs, binding.listsPager) { tab, position ->
|
||||
tab.text = getString(
|
||||
when (position) {
|
||||
TrackerTab.APPS.position -> R.string.trackers_toggle_list_apps
|
||||
else -> R.string.trackers_toggle_list_trackers
|
||||
}
|
||||
)
|
||||
}.attach()
|
||||
|
||||
setOnClickListeners()
|
||||
|
||||
listenViewModel()
|
||||
}
|
||||
|
||||
private fun setOnClickListeners() {
|
||||
binding.viewTrackersStatistics.setOnClickListener {
|
||||
viewModel.onClickViewTrackersStatistics()
|
||||
}
|
||||
|
||||
with(binding.trackersControl) {
|
||||
root.setOnClickListener {
|
||||
viewModel.onClickTrackersControl()
|
||||
}
|
||||
|
||||
switchFeature.setOnCheckedChangeListener { _, isChecked ->
|
||||
viewModel.onClickToggleTrackersContol(isChecked)
|
||||
}
|
||||
}
|
||||
|
||||
with(binding.fakeLocation) {
|
||||
root.setOnClickListener {
|
||||
viewModel.onClickFakeLocation()
|
||||
}
|
||||
|
||||
switchFeature.setOnCheckedChangeListener { _, isChecked ->
|
||||
viewModel.onClickToggleFakeLocation(isChecked)
|
||||
}
|
||||
}
|
||||
|
||||
with(binding.ipScrambling) {
|
||||
root.setOnClickListener {
|
||||
viewModel.onClickIpScrambling()
|
||||
}
|
||||
|
||||
switchFeature.setOnCheckedChangeListener { _, isChecked ->
|
||||
viewModel.onClickToggleIpScrambling(isChecked)
|
||||
}
|
||||
}
|
||||
|
||||
binding.appsPermissions.setOnClickListener {
|
||||
viewModel.onClickAppsPermissions()
|
||||
}
|
||||
}
|
||||
|
||||
private fun listenViewModel() {
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect { event ->
|
||||
when (event) {
|
||||
is SingleEvent.ToastMessageSingleEvent ->
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
getString(event.message, *event.args.toTypedArray()),
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.navigate.collect(findNavController()::navigate)
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNavigateUp(): Boolean {
|
||||
requireActivity().finish()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun render(state: DashboardState) {
|
||||
binding.dataBlockedTrackers.number.text = numberFormatter.format(state.blockedCallsCount)
|
||||
binding.dataApps.number.text = state.appsWithCallsCount.toString()
|
||||
|
||||
with(binding.trackersControl) {
|
||||
switchFeature.isChecked = state.trackerMode != FeatureMode.VULNERABLE
|
||||
|
||||
stateLabel.setText(
|
||||
when (state.trackerMode) {
|
||||
FeatureMode.DENIED -> R.string.dashboard_state_trackers_on
|
||||
FeatureMode.VULNERABLE -> R.string.dashboard_state_trackers_off
|
||||
FeatureMode.CUSTOM -> R.string.dashboard_state_trackers_custom
|
||||
}
|
||||
)
|
||||
|
||||
stateLabel.setTextColor(getStateColor(state.trackerMode != FeatureMode.VULNERABLE))
|
||||
}
|
||||
|
||||
with(binding.fakeLocation) {
|
||||
switchFeature.isChecked = state.locationMode != FeatureMode.VULNERABLE
|
||||
stateLabel.setText(
|
||||
when (state.locationMode) {
|
||||
FeatureMode.DENIED -> R.string.dashboard_state_geolocation_on
|
||||
FeatureMode.VULNERABLE -> R.string.dashboard_state_geolocation_off
|
||||
FeatureMode.CUSTOM -> R.string.dashboard_state_trackers_custom
|
||||
}
|
||||
)
|
||||
stateLabel.setTextColor(getStateColor(state.locationMode != FeatureMode.VULNERABLE))
|
||||
}
|
||||
|
||||
with(binding.ipScrambling) {
|
||||
switchFeature.isChecked = state.ipScramblingMode.isChecked
|
||||
|
||||
val isLoading = state.ipScramblingMode.isLoading
|
||||
switchFeature.isEnabled = (state.ipScramblingMode != FeatureState.STOPPING)
|
||||
|
||||
stateLoader.isVisible = isLoading
|
||||
stateLabel.visibility = if (!isLoading) View.VISIBLE else View.INVISIBLE
|
||||
|
||||
stateLabel.setText(
|
||||
if (state.ipScramblingMode == FeatureState.ON) {
|
||||
R.string.dashboard_state_ipaddress_on
|
||||
} else {
|
||||
R.string.dashboard_state_ipaddress_off
|
||||
}
|
||||
)
|
||||
stateLabel.setTextColor(getStateColor(state.ipScramblingMode == FeatureState.ON))
|
||||
}
|
||||
|
||||
tabAdapter.updateDataSet(state)
|
||||
}
|
||||
|
||||
private fun getStateColor(isActive: Boolean): Int {
|
||||
return getColor(
|
||||
requireContext(),
|
||||
if (isActive) {
|
||||
R.color.green_valid
|
||||
} else {
|
||||
R.color.red_off
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
/*
|
||||
* Copyright (C) 2024 MURENA SAS
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.dashboard
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.AppWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackerWithCount
|
||||
|
||||
data class DashboardState(
|
||||
val trackerMode: FeatureMode = FeatureMode.VULNERABLE,
|
||||
val locationMode: FeatureMode = FeatureMode.VULNERABLE,
|
||||
val ipScramblingMode: FeatureState = FeatureState.STOPPING,
|
||||
val blockedCallsCount: Int = 0,
|
||||
val appsWithCallsCount: Int = 0,
|
||||
val shameApps: List<AppWithCount> = emptyList(),
|
||||
val shameTrackers: List<TrackerWithCount> = emptyList()
|
||||
)
|
|
@ -0,0 +1,163 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.dashboard
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavDirections
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersAndAppsListsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersScreenUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.features.trackers.Period
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackerTab
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.mapLatest
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class DashboardViewModel(
|
||||
private val getPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
|
||||
private val trackersStatisticsUseCase: TrackersStatisticsUseCase,
|
||||
private val trackersAndAppsListsUseCase: TrackersAndAppsListsUseCase,
|
||||
private val trackersScreenUseCase: TrackersScreenUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow(DashboardState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
private val _navigate = MutableSharedFlow<NavDirections>()
|
||||
val navigate = _navigate.asSharedFlow()
|
||||
init {
|
||||
viewModelScope.launch(Dispatchers.IO) { trackersStatisticsUseCase.initAppList() }
|
||||
}
|
||||
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
|
||||
merge(
|
||||
getPrivacyStateUseCase.ipScramblingMode.map {
|
||||
_state.update { s -> s.copy(ipScramblingMode = it) }
|
||||
},
|
||||
|
||||
trackersStatisticsUseCase.listenUpdates().mapLatest {
|
||||
fetchStatistics()
|
||||
},
|
||||
|
||||
getPrivacyStateUseCase.trackerMode.map {
|
||||
_state.update { s -> s.copy(trackerMode = it) }
|
||||
},
|
||||
getPrivacyStateUseCase.locationMode.map {
|
||||
_state.update { s -> s.copy(locationMode = it) }
|
||||
},
|
||||
getPrivacyStateUseCase.otherVpnRunning.map {
|
||||
_singleEvents.emit(
|
||||
SingleEvent.ToastMessageSingleEvent(
|
||||
R.string.ipscrambling_error_always_on_vpn_already_running,
|
||||
listOf(it.label ?: "")
|
||||
)
|
||||
)
|
||||
}
|
||||
).collect {}
|
||||
}
|
||||
|
||||
fun onClickViewTrackersStatistics() = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoTrackersFragment())
|
||||
}
|
||||
|
||||
fun onClickTrackersControl() = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoTrackersFragment())
|
||||
}
|
||||
|
||||
fun onClickToggleTrackersContol(enabled: Boolean) = viewModelScope.launch(Dispatchers.IO) {
|
||||
getPrivacyStateUseCase.toggleTrackers(enabled)
|
||||
}
|
||||
|
||||
fun onClickFakeLocation() = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoFakeLocationFragment())
|
||||
}
|
||||
|
||||
fun onClickToggleFakeLocation(enabled: Boolean) = viewModelScope.launch(Dispatchers.IO) {
|
||||
getPrivacyStateUseCase.toggleLocation(enabled)
|
||||
}
|
||||
|
||||
fun onClickIpScrambling() = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoInternetPrivacyFragment())
|
||||
}
|
||||
|
||||
fun onClickToggleIpScrambling(enabled: Boolean) = viewModelScope.launch(Dispatchers.IO) {
|
||||
getPrivacyStateUseCase.toggleIpScrambling(enabled)
|
||||
}
|
||||
|
||||
fun onClickAppsPermissions() = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoSettingsPermissionsActivity())
|
||||
}
|
||||
|
||||
fun onClickShameApp(app: DisplayableApp) = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoAppTrackersFragment(appId = app.id))
|
||||
}
|
||||
|
||||
fun onClickShameTracker(tracker: Tracker) = viewModelScope.launch {
|
||||
_navigate.emit(DashboardFragmentDirections.gotoTrackerDetailsFragment(trackerId = tracker.id))
|
||||
}
|
||||
|
||||
fun onClickViewAllApps() = viewModelScope.launch {
|
||||
trackersScreenUseCase.preselectTab(Period.MONTH.ordinal, TrackerTab.APPS.ordinal)
|
||||
_navigate.emit(DashboardFragmentDirections.gotoTrackersFragment())
|
||||
}
|
||||
|
||||
fun onClickViewAllTrackers() = viewModelScope.launch {
|
||||
trackersScreenUseCase.preselectTab(Period.MONTH.ordinal, TrackerTab.TRACKERS.ordinal)
|
||||
_navigate.emit(DashboardFragmentDirections.gotoTrackersFragment())
|
||||
}
|
||||
private suspend fun fetchStatistics() = withContext(Dispatchers.IO) {
|
||||
val blockedCallsCount = trackersStatisticsUseCase.getLastMonthBlockedLeaksCount()
|
||||
|
||||
val appsWithBlockedLeaksCount = trackersStatisticsUseCase.getLastMonthAppsWithBlockedLeaksCount()
|
||||
|
||||
val lists = trackersAndAppsListsUseCase.buildWallOfShame()
|
||||
_state.update {
|
||||
it.copy(
|
||||
blockedCallsCount = blockedCallsCount,
|
||||
appsWithCallsCount = appsWithBlockedLeaksCount,
|
||||
shameApps = lists.appsWithTrackers,
|
||||
shameTrackers = lists.trackers
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ToastMessageSingleEvent(
|
||||
@StringRes val message: Int,
|
||||
val args: List<Any> = emptyList()
|
||||
) : SingleEvent()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,185 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.features.dashboard
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.divider.MaterialDividerItemDecoration
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.BigNumberFormatter
|
||||
import foundation.e.advancedprivacy.common.BindingListAdapter
|
||||
import foundation.e.advancedprivacy.common.BindingViewHolder
|
||||
import foundation.e.advancedprivacy.common.extensions.dpToPx
|
||||
import foundation.e.advancedprivacy.databinding.DashboardShameListBinding
|
||||
import foundation.e.advancedprivacy.databinding.TrackersItemAppBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.AppWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackerWithCount
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackerTab
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
class ShameListsTabPagerAdapter(
|
||||
private val onClickShameApp: (DisplayableApp) -> Unit,
|
||||
private val onClickShameTracker: (Tracker) -> Unit,
|
||||
private val onClickViewAllApps: () -> Unit,
|
||||
private val onClickViewAllTrackers: () -> Unit
|
||||
) : RecyclerView.Adapter<ShameListsTabPagerAdapter.ListsTabViewHolder>() {
|
||||
private var uiState: DashboardState = DashboardState()
|
||||
|
||||
fun updateDataSet(state: DashboardState) {
|
||||
uiState = state
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun getItemViewType(position: Int): Int = position
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListsTabViewHolder {
|
||||
val view = DashboardShameListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
|
||||
return when (viewType) {
|
||||
TrackerTab.APPS.position -> {
|
||||
ListsTabViewHolder.AppsListViewHolder(view, onClickShameApp, onClickViewAllApps)
|
||||
}
|
||||
else -> {
|
||||
ListsTabViewHolder.TrackersListViewHolder(view, onClickShameTracker, onClickViewAllTrackers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return 2
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: ListsTabViewHolder, position: Int) {
|
||||
when (position) {
|
||||
TrackerTab.APPS.position -> {
|
||||
(holder as ListsTabViewHolder.AppsListViewHolder).onBind(uiState)
|
||||
}
|
||||
TrackerTab.TRACKERS.position -> {
|
||||
(holder as ListsTabViewHolder.TrackersListViewHolder).onBind(uiState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed class ListsTabViewHolder(view: View) : RecyclerView.ViewHolder(view) {
|
||||
protected val numberFormatter: BigNumberFormatter by lazy { BigNumberFormatter(itemView.context) }
|
||||
|
||||
protected fun setupRecyclerView(recyclerView: RecyclerView) {
|
||||
recyclerView.apply {
|
||||
layoutManager = LinearLayoutManager(context)
|
||||
setHasFixedSize(true)
|
||||
isNestedScrollingEnabled = false
|
||||
addItemDecoration(
|
||||
MaterialDividerItemDecoration(context, LinearLayoutManager.VERTICAL).apply {
|
||||
dividerColor = ContextCompat.getColor(context, R.color.divider)
|
||||
dividerInsetStart = 16.dpToPx(context)
|
||||
dividerInsetEnd = 16.dpToPx(context)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class AppsListViewHolder(
|
||||
private val binding: DashboardShameListBinding,
|
||||
private val onClickShameApp: (DisplayableApp) -> Unit,
|
||||
private val onClickViewAllApps: () -> Unit
|
||||
) : ListsTabViewHolder(binding.root) {
|
||||
|
||||
private val adapter = object : BindingListAdapter<TrackersItemAppBinding, AppWithCount>() {
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder<TrackersItemAppBinding> {
|
||||
return BindingViewHolder(
|
||||
TrackersItemAppBinding.inflate(
|
||||
LayoutInflater.from(parent.context),
|
||||
parent,
|
||||
false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: BindingViewHolder<TrackersItemAppBinding>, position: Int) {
|
||||
val item = dataSet[position]
|
||||
holder.binding.icon.setImageDrawable(item.app.icon)
|
||||
holder.binding.title.text = item.app.label
|
||||
holder.binding.counts.text = itemView.context.getString(
|
||||
R.string.dashboard_wall_of_shame_app_calls,
|
||||
numberFormatter.format(item.count)
|
||||
)
|
||||
holder.binding.root.setOnClickListener { onClickShameApp(item.app) }
|
||||
}
|
||||
}
|
||||
init {
|
||||
setupRecyclerView(binding.list)
|
||||
binding.list.adapter = adapter
|
||||
binding.viewAll.apply {
|
||||
text = binding.root.context.getString(R.string.dashboard_view_all_apps)
|
||||
setOnClickListener { onClickViewAllApps() }
|
||||
}
|
||||
}
|
||||
|
||||
fun onBind(uiState: DashboardState) {
|
||||
adapter.dataSet = uiState.shameApps
|
||||
}
|
||||
}
|
||||
|
||||
class TrackersListViewHolder(
|
||||
private val binding: DashboardShameListBinding,
|
||||
private val onClickShameTracker: (Tracker) -> Unit,
|
||||
private val onClickViewAllTrackers: () -> Unit
|
||||
) : ListsTabViewHolder(binding.root) {
|
||||
|
||||
private val adapter = object : BindingListAdapter<TrackersItemAppBinding, TrackerWithCount>() {
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder<TrackersItemAppBinding> {
|
||||
return BindingViewHolder(
|
||||
TrackersItemAppBinding.inflate(
|
||||
LayoutInflater.from(parent.context),
|
||||
parent,
|
||||
false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: BindingViewHolder<TrackersItemAppBinding>, position: Int) {
|
||||
val item = dataSet[position]
|
||||
holder.binding.icon.isVisible = false
|
||||
holder.binding.title.text = item.tracker.label
|
||||
holder.binding.counts.text = itemView.context.getString(
|
||||
R.string.dashboard_wall_of_shame_trackers_calls,
|
||||
numberFormatter.format(item.count)
|
||||
)
|
||||
holder.binding.root.setOnClickListener { onClickShameTracker(item.tracker) }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setupRecyclerView(binding.list)
|
||||
binding.list.adapter = adapter
|
||||
binding.viewAll.apply {
|
||||
text = binding.root.context.getString(R.string.dashboard_view_all_trackers)
|
||||
setOnClickListener { onClickViewAllTrackers() }
|
||||
}
|
||||
}
|
||||
|
||||
fun onBind(uiState: DashboardState) {
|
||||
adapter.dataSet = uiState.shameTrackers
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,174 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.internetprivacy
|
||||
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.AdapterView
|
||||
import android.widget.ArrayAdapter
|
||||
import android.widget.Toast
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.common.setToolTipForAsterisk
|
||||
import foundation.e.advancedprivacy.databinding.FragmentInternetActivityPolicyBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import java.util.Locale
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
|
||||
class InternetPrivacyFragment : NavToolbarFragment(R.layout.fragment_internet_activity_policy) {
|
||||
|
||||
private val viewModel: InternetPrivacyViewModel by viewModel()
|
||||
|
||||
private var _binding: FragmentInternetActivityPolicyBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
_binding = FragmentInternetActivityPolicyBinding.bind(view)
|
||||
|
||||
binding.apps.apply {
|
||||
layoutManager = LinearLayoutManager(requireContext())
|
||||
setHasFixedSize(true)
|
||||
adapter = ToggleAppsAdapter(R.layout.item_app_toggle) { app ->
|
||||
viewModel.onClickToggleAppIpScrambled(app)
|
||||
}
|
||||
}
|
||||
|
||||
binding.radioUseRealIp.radiobutton.setOnClickListener {
|
||||
viewModel.submitAction(InternetPrivacyViewModel.Action.UseRealIPAction)
|
||||
}
|
||||
|
||||
binding.radioUseHiddenIp.radiobutton.setOnClickListener {
|
||||
viewModel.submitAction(InternetPrivacyViewModel.Action.UseHiddenIPAction)
|
||||
}
|
||||
|
||||
setToolTipForAsterisk(
|
||||
textView = binding.ipscramblingSelectApps,
|
||||
textId = R.string.ipscrambling_select_app,
|
||||
tooltipTextId = R.string.ipscrambling_app_list_infos
|
||||
)
|
||||
|
||||
binding.ipscramblingSelectLocation.apply {
|
||||
adapter = ArrayAdapter(
|
||||
requireContext(), android.R.layout.simple_spinner_item,
|
||||
viewModel.availablesLocationsIds.map {
|
||||
if (it == "") {
|
||||
getString(R.string.ipscrambling_any_location)
|
||||
} else {
|
||||
Locale("", it).displayCountry
|
||||
}
|
||||
}
|
||||
).apply {
|
||||
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
|
||||
}
|
||||
|
||||
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
|
||||
override fun onItemSelected(parentView: AdapterView<*>, selectedItemView: View?, position: Int, id: Long) {
|
||||
viewModel.submitAction(
|
||||
InternetPrivacyViewModel.Action.SelectLocationAction(
|
||||
position
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onNothingSelected(parentView: AdapterView<*>?) {}
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect { event ->
|
||||
when (event) {
|
||||
is InternetPrivacyViewModel.SingleEvent.ErrorEvent -> {
|
||||
displayToast(getString(event.errorResId, *event.args.toTypedArray()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun render(state: InternetPrivacyState) {
|
||||
binding.radioUseHiddenIp.radiobutton.apply {
|
||||
isChecked = state.mode.isChecked
|
||||
isEnabled = state.mode != FeatureState.STARTING
|
||||
}
|
||||
binding.radioUseRealIp.radiobutton.apply {
|
||||
isChecked = !state.mode.isChecked
|
||||
isEnabled = state.mode != FeatureState.STOPPING
|
||||
}
|
||||
|
||||
binding.ipscramblingSelectLocation.setSelection(state.selectedLocationPosition)
|
||||
|
||||
// TODO: this should not be mandatory.
|
||||
binding.apps.post {
|
||||
(binding.apps.adapter as ToggleAppsAdapter?)?.setData(
|
||||
list = state.torToggleableApp,
|
||||
isEnabled = state.mode == FeatureState.ON
|
||||
)
|
||||
}
|
||||
|
||||
val viewIdsToHide = listOf(
|
||||
binding.ipscramblingLocationLabel,
|
||||
binding.selectLocationContainer,
|
||||
binding.ipscramblingSelectLocation,
|
||||
binding.ipscramblingSelectApps,
|
||||
binding.apps
|
||||
)
|
||||
|
||||
when {
|
||||
state.mode.isLoading ||
|
||||
state.torToggleableApp.isEmpty() -> {
|
||||
binding.loader.visibility = View.VISIBLE
|
||||
viewIdsToHide.forEach { it.visibility = View.GONE }
|
||||
}
|
||||
else -> {
|
||||
binding.loader.visibility = View.GONE
|
||||
viewIdsToHide.forEach { it.visibility = View.VISIBLE }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
_binding = null
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.internetprivacy
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
|
||||
data class InternetPrivacyState(
|
||||
val mode: FeatureState = FeatureState.OFF,
|
||||
val torToggleableApp: List<ToggleableApp> = emptyList(),
|
||||
val selectedLocation: String = "",
|
||||
val availableLocationIds: List<String> = emptyList(),
|
||||
val forceRedraw: Boolean = false
|
||||
) {
|
||||
val selectedLocationPosition get() = availableLocationIds.indexOf(selectedLocation)
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.internetprivacy
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.IpScramblingStateUseCase
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class InternetPrivacyViewModel(
|
||||
private val getQuickPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
|
||||
private val ipScramblingStateUseCase: IpScramblingStateUseCase
|
||||
) : ViewModel() {
|
||||
companion object {
|
||||
private const val WARNING_LOADING_LONG_DELAY = 5 * 1000L
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow(InternetPrivacyState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
val availablesLocationsIds = listOf("", *ipScramblingStateUseCase.availablesLocations.toTypedArray())
|
||||
|
||||
init {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
mode = ipScramblingStateUseCase.internetPrivacyMode.value,
|
||||
availableLocationIds = availablesLocationsIds,
|
||||
selectedLocation = ipScramblingStateUseCase.exitCountry
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
|
||||
launch {
|
||||
merge(
|
||||
ipScramblingStateUseCase.getTorToggleableApp().map { apps ->
|
||||
_state.update { it.copy(torToggleableApp = apps) }
|
||||
},
|
||||
ipScramblingStateUseCase.internetPrivacyMode.map {
|
||||
_state.update { s -> s.copy(mode = it) }
|
||||
}
|
||||
).collect {}
|
||||
}
|
||||
|
||||
launch {
|
||||
ipScramblingStateUseCase.internetPrivacyMode
|
||||
.map { it == FeatureState.STARTING }
|
||||
.debounce(WARNING_LOADING_LONG_DELAY)
|
||||
.collect {
|
||||
if (it) {
|
||||
_singleEvents.emit(
|
||||
SingleEvent.ErrorEvent(R.string.ipscrambling_warning_starting_long)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
launch {
|
||||
getQuickPrivacyStateUseCase.otherVpnRunning.collect {
|
||||
_singleEvents.emit(
|
||||
SingleEvent.ErrorEvent(
|
||||
R.string.ipscrambling_error_always_on_vpn_already_running,
|
||||
listOf(it.label ?: "")
|
||||
)
|
||||
)
|
||||
_state.update { it.copy(forceRedraw = !it.forceRedraw) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun submitAction(action: Action) = viewModelScope.launch {
|
||||
when (action) {
|
||||
is Action.UseRealIPAction -> actionUseRealIP()
|
||||
is Action.UseHiddenIPAction -> actionUseHiddenIP()
|
||||
is Action.SelectLocationAction -> actionSelectLocation(action)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun actionUseRealIP() {
|
||||
ipScramblingStateUseCase.toggle(hideIp = false)
|
||||
}
|
||||
|
||||
private suspend fun actionUseHiddenIP() {
|
||||
ipScramblingStateUseCase.toggle(hideIp = true)
|
||||
}
|
||||
|
||||
fun onClickToggleAppIpScrambled(app: DisplayableApp) = viewModelScope.launch(Dispatchers.IO) {
|
||||
ipScramblingStateUseCase.toggleBypassTor(app)
|
||||
}
|
||||
|
||||
private suspend fun actionSelectLocation(action: Action.SelectLocationAction) = withContext(Dispatchers.IO) {
|
||||
val locationId = _state.value.availableLocationIds[action.position]
|
||||
ipScramblingStateUseCase.setExitCountry(locationId)
|
||||
_state.update { it.copy(selectedLocation = locationId) }
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ErrorEvent(
|
||||
@StringRes val errorResId: Int,
|
||||
val args: List<Any> = emptyList()
|
||||
) : SingleEvent()
|
||||
}
|
||||
|
||||
sealed class Action {
|
||||
object UseRealIPAction : Action()
|
||||
object UseHiddenIPAction : Action()
|
||||
data class SelectLocationAction(val position: Int) : Action()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
/*
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.internetprivacy
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.CheckBox
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
|
||||
class ToggleAppsAdapter(
|
||||
private val itemsLayout: Int,
|
||||
private val listener: (DisplayableApp) -> Unit
|
||||
) :
|
||||
RecyclerView.Adapter<ToggleAppsAdapter.ViewHolder>() {
|
||||
|
||||
class ViewHolder(view: View, private val listener: (DisplayableApp) -> Unit) : RecyclerView.ViewHolder(view) {
|
||||
val appName: TextView = view.findViewById(R.id.title)
|
||||
|
||||
val togglePermission: CheckBox = view.findViewById(R.id.toggle)
|
||||
|
||||
fun bind(item: ToggleableApp, isEnabled: Boolean) {
|
||||
appName.text = item.app.label
|
||||
togglePermission.isChecked = item.isOn
|
||||
togglePermission.isEnabled = isEnabled
|
||||
|
||||
itemView.findViewById<ImageView>(R.id.icon).setImageDrawable(item.app.icon)
|
||||
togglePermission.setOnClickListener { listener(item.app) }
|
||||
}
|
||||
}
|
||||
|
||||
var dataSet: List<ToggleableApp> = emptyList()
|
||||
set(value) {
|
||||
field = value
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
var isEnabled: Boolean = true
|
||||
|
||||
fun setData(list: List<ToggleableApp>, isEnabled: Boolean = true) {
|
||||
this.isEnabled = isEnabled
|
||||
dataSet = list
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(itemsLayout, parent, false)
|
||||
return ViewHolder(view, listener)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
val permission = dataSet[position]
|
||||
holder.bind(permission, isEnabled)
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = dataSet.size
|
||||
}
|
|
@ -0,0 +1,446 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.location
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.location.Location
|
||||
import android.os.Bundle
|
||||
import android.text.Editable
|
||||
import android.view.View
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.NonNull
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.textfield.TextInputLayout
|
||||
import com.google.android.material.textfield.TextInputLayout.END_ICON_CUSTOM
|
||||
import com.google.android.material.textfield.TextInputLayout.END_ICON_NONE
|
||||
import com.mapbox.android.gestures.MoveGestureDetector
|
||||
import com.mapbox.mapboxsdk.Mapbox
|
||||
import com.mapbox.mapboxsdk.WellKnownTileServer
|
||||
import com.mapbox.mapboxsdk.camera.CameraPosition
|
||||
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
|
||||
import com.mapbox.mapboxsdk.geometry.LatLng
|
||||
import com.mapbox.mapboxsdk.location.LocationComponent
|
||||
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
|
||||
import com.mapbox.mapboxsdk.location.modes.CameraMode
|
||||
import com.mapbox.mapboxsdk.location.modes.RenderMode
|
||||
import com.mapbox.mapboxsdk.maps.MapboxMap
|
||||
import com.mapbox.mapboxsdk.maps.Style
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.common.setToolTipForAsterisk
|
||||
import foundation.e.advancedprivacy.databinding.FragmentFakeLocationBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.LocationMode
|
||||
import foundation.e.advancedprivacy.features.internetprivacy.ToggleAppsAdapter
|
||||
import foundation.e.advancedprivacy.features.location.FakeLocationViewModel.Action
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import timber.log.Timber
|
||||
|
||||
class FakeLocationFragment : NavToolbarFragment(R.layout.fragment_fake_location) {
|
||||
|
||||
private var isFirstLaunch: Boolean = true
|
||||
|
||||
private val viewModel: FakeLocationViewModel by viewModel()
|
||||
|
||||
private var _binding: FragmentFakeLocationBinding? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
private var mapboxMap: MapboxMap? = null
|
||||
private var locationComponent: LocationComponent? = null
|
||||
|
||||
private var inputJob: Job? = null
|
||||
|
||||
private var updateLocationJob: Job? = null
|
||||
|
||||
private val locationPermissionRequest = registerForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { permissions ->
|
||||
if (permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false) ||
|
||||
permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false)
|
||||
) {
|
||||
viewModel.submitAction(Action.StartListeningLocation)
|
||||
} // TODO: else.
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val MAP_STYLE = "mapbox://styles/mapbox/outdoors-v12"
|
||||
}
|
||||
|
||||
override fun onAttach(context: Context) {
|
||||
super.onAttach(context)
|
||||
Mapbox.getInstance(requireContext(), getString(R.string.mapbox_key), WellKnownTileServer.Mapbox)
|
||||
}
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
_binding = FragmentFakeLocationBinding.bind(view)
|
||||
|
||||
binding.mapView.setup(savedInstanceState) { mapboxMap ->
|
||||
this.mapboxMap = mapboxMap
|
||||
mapboxMap.uiSettings.isRotateGesturesEnabled = false
|
||||
mapboxMap.setStyle(MAP_STYLE) { style ->
|
||||
enableLocationPlugin(style)
|
||||
|
||||
mapboxMap.addOnMoveListener(onMoveListener)
|
||||
|
||||
mapboxMap.cameraPosition = CameraPosition.Builder().zoom(8.0).build()
|
||||
|
||||
// Bind click listeners once map is ready.
|
||||
bindClickListeners()
|
||||
|
||||
render(viewModel.state.value)
|
||||
startUpdateLocationJob()
|
||||
}
|
||||
}
|
||||
|
||||
binding.apps.apply {
|
||||
layoutManager = LinearLayoutManager(requireContext())
|
||||
setHasFixedSize(true)
|
||||
adapter = ToggleAppsAdapter(R.layout.item_app_toggle) { app ->
|
||||
viewModel.onToggleApp(app)
|
||||
}
|
||||
}
|
||||
|
||||
setToolTipForAsterisk(
|
||||
textView = binding.targetedAppsSubtitles,
|
||||
textId = R.string.ipscrambling_select_app,
|
||||
tooltipTextId = R.string.location_app_list_infos
|
||||
)
|
||||
|
||||
startListening()
|
||||
}
|
||||
|
||||
private val onMoveListener = object : MapboxMap.OnMoveListener {
|
||||
private val cameraIdleListener: MapboxMap.OnCameraIdleListener =
|
||||
object : MapboxMap.OnCameraIdleListener {
|
||||
override fun onCameraIdle() {
|
||||
mapboxMap?.cameraPosition?.target?.let {
|
||||
viewModel.submitAction(
|
||||
Action.SetSpecificLocationAction(
|
||||
it.latitude.toFloat(),
|
||||
it.longitude.toFloat()
|
||||
)
|
||||
)
|
||||
startUpdateLocationJob()
|
||||
}
|
||||
mapboxMap?.removeOnCameraIdleListener(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMoveBegin(detector: MoveGestureDetector) {
|
||||
updateLocationJob?.cancel()
|
||||
updateLocationJob = null
|
||||
mapboxMap?.removeOnCameraIdleListener(cameraIdleListener)
|
||||
}
|
||||
|
||||
override fun onMove(detector: MoveGestureDetector) {}
|
||||
|
||||
override fun onMoveEnd(detector: MoveGestureDetector) {
|
||||
mapboxMap?.addOnCameraIdleListener(cameraIdleListener)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startListening() {
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect { event ->
|
||||
when (event) {
|
||||
is FakeLocationViewModel.SingleEvent.ErrorEvent -> {
|
||||
displayToast(event.error)
|
||||
}
|
||||
is FakeLocationViewModel.SingleEvent.RequestLocationPermission -> {
|
||||
// TODO for standalone: rationale dialog
|
||||
locationPermissionRequest.launch(
|
||||
arrayOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun startUpdateLocationJob() {
|
||||
updateLocationJob?.cancel()
|
||||
updateLocationJob = viewLifecycleOwner.lifecycleScope.launch {
|
||||
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
// Without this delay, onResume, map apply the updateLocation and then
|
||||
// move to an old fake location.
|
||||
delay(1000)
|
||||
viewModel.currentLocation.collect { location ->
|
||||
updateLocation(location, viewModel.state.value.mode)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validateCoordinate(inputLayout: TextInputLayout, maxValue: Float): Boolean {
|
||||
return try {
|
||||
val value = inputLayout.editText?.text?.toString()?.toFloat()!!
|
||||
|
||||
if (value > maxValue || value < -maxValue) {
|
||||
throw NumberFormatException("value $value is out of bounds")
|
||||
}
|
||||
inputLayout.error = null
|
||||
|
||||
inputLayout.setEndIconDrawable(R.drawable.ic_valid)
|
||||
inputLayout.endIconMode = END_ICON_CUSTOM
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
inputLayout.endIconMode = END_ICON_NONE
|
||||
inputLayout.error = getString(R.string.location_input_error)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateSpecificCoordinates() {
|
||||
try {
|
||||
val lat = binding.edittextLatitude.text.toString().toFloat()
|
||||
val lon = binding.edittextLongitude.text.toString().toFloat()
|
||||
if (lat <= 90f && lat >= -90f && lon <= 180f && lon >= -180f) {
|
||||
viewModel.submitAction(
|
||||
Action.SetSpecificLocationAction(
|
||||
lat,
|
||||
lon
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (e: NumberFormatException) {
|
||||
Timber.e("Unfiltered wrong lat lon format")
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
private fun onLatTextChanged(editable: Editable?) {
|
||||
if (!binding.edittextLatitude.isFocused ||
|
||||
!validateCoordinate(binding.textlayoutLatitude, 90f)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
updateSpecificCoordinates()
|
||||
}
|
||||
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
private fun onLonTextChanged(editable: Editable?) {
|
||||
if (!binding.edittextLongitude.isFocused ||
|
||||
!validateCoordinate(binding.textlayoutLongitude, 180f)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
updateSpecificCoordinates()
|
||||
}
|
||||
|
||||
private val isEditingLatLon get() = binding.edittextLongitude.isFocused || binding.edittextLatitude.isFocused
|
||||
|
||||
private val latLonOnFocusChangeListener = object : View.OnFocusChangeListener {
|
||||
override fun onFocusChange(v: View?, hasFocus: Boolean) {
|
||||
if (!isEditingLatLon) {
|
||||
(context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(
|
||||
v?.windowToken,
|
||||
0
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
private fun bindClickListeners() {
|
||||
binding.radioUseRealLocation.setOnClickListener {
|
||||
viewModel.submitAction(Action.UseRealLocationAction)
|
||||
}
|
||||
binding.radioUseRandomLocation.setOnClickListener {
|
||||
viewModel.submitAction(Action.UseRandomLocationAction)
|
||||
}
|
||||
binding.radioUseSpecificLocation.setOnClickListener {
|
||||
mapboxMap?.cameraPosition?.target?.let {
|
||||
viewModel.submitAction(
|
||||
Action.SetSpecificLocationAction(it.latitude.toFloat(), it.longitude.toFloat())
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
binding.edittextLatitude.addTextChangedListener(afterTextChanged = ::onLatTextChanged)
|
||||
binding.edittextLongitude.addTextChangedListener(afterTextChanged = ::onLonTextChanged)
|
||||
binding.edittextLatitude.onFocusChangeListener = latLonOnFocusChangeListener
|
||||
binding.edittextLongitude.onFocusChangeListener = latLonOnFocusChangeListener
|
||||
|
||||
binding.btnReset.setOnClickListener {
|
||||
viewModel.onClickResetAllApplications()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun render(state: FakeLocationState) {
|
||||
binding.radioUseRandomLocation.isChecked = state.mode == LocationMode.RANDOM_LOCATION
|
||||
|
||||
binding.radioUseSpecificLocation.isChecked = state.mode == LocationMode.SPECIFIC_LOCATION
|
||||
|
||||
binding.radioUseRealLocation.isChecked = state.mode == LocationMode.REAL_LOCATION
|
||||
|
||||
binding.mapView.isEnabled = (state.mode == LocationMode.SPECIFIC_LOCATION)
|
||||
|
||||
if (state.mode == LocationMode.REAL_LOCATION) {
|
||||
binding.centeredMarker.isVisible = false
|
||||
} else {
|
||||
binding.mapLoader.isVisible = false
|
||||
binding.mapOverlay.isVisible = state.mode != LocationMode.SPECIFIC_LOCATION
|
||||
binding.centeredMarker.isVisible = true
|
||||
mapboxMap?.moveCamera(
|
||||
CameraUpdateFactory.newLatLng(
|
||||
LatLng(
|
||||
state.specificLatitude?.toDouble() ?: 0.0,
|
||||
state.specificLongitude?.toDouble() ?: 0.0
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
binding.textlayoutLatitude.isVisible = (state.mode == LocationMode.SPECIFIC_LOCATION)
|
||||
binding.textlayoutLongitude.isVisible = (state.mode == LocationMode.SPECIFIC_LOCATION)
|
||||
|
||||
if (!isEditingLatLon) {
|
||||
binding.edittextLatitude.setText(state.specificLatitude?.toString())
|
||||
binding.edittextLongitude.setText(state.specificLongitude?.toString())
|
||||
}
|
||||
|
||||
binding.apps.post {
|
||||
(binding.apps.adapter as ToggleAppsAdapter?)?.setData(
|
||||
list = state.appsWithBlackList,
|
||||
isEnabled = state.mode != LocationMode.REAL_LOCATION
|
||||
)
|
||||
}
|
||||
|
||||
binding.btnReset.isVisible = state.showResetBlacklist
|
||||
binding.btnReset.isClickable = state.showResetBlacklist
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun updateLocation(lastLocation: Location?, mode: LocationMode) {
|
||||
lastLocation?.let { location ->
|
||||
locationComponent?.isLocationComponentEnabled = true
|
||||
locationComponent?.forceLocationUpdate(location)
|
||||
|
||||
if (mode == LocationMode.REAL_LOCATION) {
|
||||
binding.mapLoader.isVisible = false
|
||||
binding.mapOverlay.isVisible = false
|
||||
|
||||
val update = CameraUpdateFactory.newLatLng(
|
||||
LatLng(location.latitude, location.longitude)
|
||||
)
|
||||
if (isFirstLaunch) {
|
||||
mapboxMap?.moveCamera(update)
|
||||
isFirstLaunch = false
|
||||
} else {
|
||||
mapboxMap?.animateCamera(update)
|
||||
}
|
||||
}
|
||||
} ?: run {
|
||||
locationComponent?.isLocationComponentEnabled = false
|
||||
if (mode == LocationMode.REAL_LOCATION) {
|
||||
binding.mapLoader.isVisible = true
|
||||
binding.mapOverlay.isVisible = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun enableLocationPlugin(@NonNull loadedMapStyle: Style) {
|
||||
// Check if permissions are enabled and if not request
|
||||
locationComponent = mapboxMap?.locationComponent
|
||||
locationComponent?.activateLocationComponent(
|
||||
LocationComponentActivationOptions.builder(
|
||||
requireContext(),
|
||||
loadedMapStyle
|
||||
).useDefaultLocationEngine(false).build()
|
||||
)
|
||||
locationComponent?.isLocationComponentEnabled = true
|
||||
locationComponent?.cameraMode = CameraMode.NONE
|
||||
locationComponent?.renderMode = RenderMode.NORMAL
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
binding.mapView.onStart()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
viewModel.submitAction(Action.StartListeningLocation)
|
||||
binding.mapView.onResume()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
viewModel.submitAction(Action.StopListeningLocation)
|
||||
binding.mapView.onPause()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
binding.mapView.onStop()
|
||||
}
|
||||
|
||||
override fun onLowMemory() {
|
||||
super.onLowMemory()
|
||||
binding.mapView.onLowMemory()
|
||||
}
|
||||
|
||||
override fun onDestroyView() {
|
||||
super.onDestroyView()
|
||||
binding.mapView.onDestroy()
|
||||
mapboxMap = null
|
||||
locationComponent = null
|
||||
inputJob = null
|
||||
_binding = null
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.location
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.util.AttributeSet
|
||||
import android.view.MotionEvent
|
||||
import com.mapbox.mapboxsdk.maps.MapView
|
||||
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback
|
||||
|
||||
class FakeLocationMapView @JvmOverloads constructor(
|
||||
context: Context,
|
||||
attrs: AttributeSet? = null,
|
||||
defStyleAttr: Int = 0
|
||||
) : MapView(context, attrs, defStyleAttr) {
|
||||
|
||||
/**
|
||||
* Overrides onTouchEvent because this MapView is part of a scroll view
|
||||
* and we want this map view to consume all touch events originating on this view.
|
||||
*/
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent?): Boolean {
|
||||
when (event?.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
parent.requestDisallowInterceptTouchEvent(true)
|
||||
requestFocus()
|
||||
}
|
||||
MotionEvent.ACTION_UP -> parent.requestDisallowInterceptTouchEvent(false)
|
||||
}
|
||||
super.onTouchEvent(event)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
fun FakeLocationMapView.setup(savedInstanceState: Bundle?, callback: OnMapReadyCallback) = this.apply {
|
||||
onCreate(savedInstanceState)
|
||||
getMapAsync(callback)
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.location
|
||||
|
||||
import android.location.Location
|
||||
import foundation.e.advancedprivacy.domain.entities.LocationMode
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
|
||||
data class FakeLocationState(
|
||||
val mode: LocationMode = LocationMode.REAL_LOCATION,
|
||||
val currentLocation: Location? = null,
|
||||
val specificLatitude: Float? = null,
|
||||
val specificLongitude: Float? = null,
|
||||
val forceRefresh: Boolean = false,
|
||||
val appsWithBlackList: List<ToggleableApp> = emptyList(),
|
||||
val showResetBlacklist: Boolean = false
|
||||
)
|
|
@ -0,0 +1,131 @@
|
|||
/*
|
||||
* Copyright (C) 2021, 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.location
|
||||
|
||||
import android.location.Location
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.usecases.FakeLocationStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.ListenLocationUseCase
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class FakeLocationViewModel(
|
||||
private val fakeLocationStateUseCase: FakeLocationStateUseCase,
|
||||
private val listenLocationUseCase: ListenLocationUseCase
|
||||
) : ViewModel() {
|
||||
companion object {
|
||||
private val SET_SPECIFIC_LOCATION_DELAY = 200.milliseconds
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow(FakeLocationState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
val currentLocation: StateFlow<Location?> = listenLocationUseCase.currentLocation
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
private val specificLocationInputFlow = MutableSharedFlow<Action.SetSpecificLocationAction>()
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.Main) {
|
||||
launch {
|
||||
merge(
|
||||
fakeLocationStateUseCase.configuredLocationMode.map { (mode, lat, lon) ->
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
mode = mode,
|
||||
specificLatitude = lat,
|
||||
specificLongitude = lon
|
||||
)
|
||||
}
|
||||
},
|
||||
specificLocationInputFlow
|
||||
.debounce(SET_SPECIFIC_LOCATION_DELAY).map { action ->
|
||||
fakeLocationStateUseCase.setSpecificLocation(action.latitude, action.longitude)
|
||||
},
|
||||
fakeLocationStateUseCase.appsWithBlacklist().map { apps ->
|
||||
_state.update { s -> s.copy(appsWithBlackList = apps) }
|
||||
},
|
||||
fakeLocationStateUseCase.canResetBlacklist().map {
|
||||
_state.update { s -> s.copy(showResetBlacklist = it) }
|
||||
}
|
||||
).collect {}
|
||||
}
|
||||
}
|
||||
|
||||
fun submitAction(action: Action) = viewModelScope.launch {
|
||||
when (action) {
|
||||
is Action.StartListeningLocation -> actionStartListeningLocation()
|
||||
is Action.StopListeningLocation -> listenLocationUseCase.stopListeningLocation()
|
||||
is Action.SetSpecificLocationAction -> setSpecificLocation(action)
|
||||
is Action.UseRandomLocationAction -> fakeLocationStateUseCase.setRandomLocation()
|
||||
is Action.UseRealLocationAction ->
|
||||
fakeLocationStateUseCase.stopFakeLocation()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun actionStartListeningLocation() {
|
||||
val started = listenLocationUseCase.startListeningLocation()
|
||||
if (!started) {
|
||||
_singleEvents.emit(SingleEvent.RequestLocationPermission)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun setSpecificLocation(action: Action.SetSpecificLocationAction) {
|
||||
specificLocationInputFlow.emit(action)
|
||||
}
|
||||
|
||||
fun onToggleApp(app: DisplayableApp) = viewModelScope.launch(Dispatchers.IO) {
|
||||
fakeLocationStateUseCase.toggleBlacklist(app)
|
||||
}
|
||||
|
||||
fun onClickResetAllApplications() = viewModelScope.launch(Dispatchers.IO) {
|
||||
fakeLocationStateUseCase.resetBlacklist()
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
object RequestLocationPermission : SingleEvent()
|
||||
data class ErrorEvent(val error: String) : SingleEvent()
|
||||
}
|
||||
|
||||
sealed class Action {
|
||||
object StartListeningLocation : Action()
|
||||
object StopListeningLocation : Action()
|
||||
object UseRealLocationAction : Action()
|
||||
object UseRandomLocationAction : Action()
|
||||
data class SetSpecificLocationAction(
|
||||
val latitude: Float,
|
||||
val longitude: Float
|
||||
) : Action()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,191 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.google.android.material.divider.MaterialDividerItemDecoration
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.BindingListAdapter
|
||||
import foundation.e.advancedprivacy.common.BindingViewHolder
|
||||
import foundation.e.advancedprivacy.common.extensions.dpToPx
|
||||
import foundation.e.advancedprivacy.databinding.TrackersAppsListBinding
|
||||
import foundation.e.advancedprivacy.databinding.TrackersItemAppBinding
|
||||
import foundation.e.advancedprivacy.databinding.TrackersListBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.AppWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackerWithCount
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
class ListsTabPagerAdapter(
|
||||
private val onClickTracker: (Tracker) -> Unit,
|
||||
private val onClickApp: (DisplayableApp) -> Unit,
|
||||
private val onToggleHideNoTrackersApps: () -> Unit
|
||||
) : RecyclerView.Adapter<ListsTabPagerAdapter.ListsTabViewHolder>() {
|
||||
private var uiState: TrackersPeriodState = TrackersPeriodState()
|
||||
|
||||
fun updateDataSet(state: TrackersPeriodState) {
|
||||
uiState = state
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun getItemViewType(position: Int): Int = position
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListsTabViewHolder {
|
||||
val inflater = LayoutInflater.from(parent.context)
|
||||
return when (viewType) {
|
||||
TrackerTab.APPS.position -> {
|
||||
ListsTabViewHolder.AppsListViewHolder(
|
||||
TrackersAppsListBinding.inflate(inflater, parent, false),
|
||||
onClickApp,
|
||||
onToggleHideNoTrackersApps
|
||||
)
|
||||
}
|
||||
else -> {
|
||||
ListsTabViewHolder.TrackersListViewHolder(
|
||||
TrackersListBinding.inflate(inflater, parent, false),
|
||||
onClickTracker
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return 2
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: ListsTabViewHolder, position: Int) {
|
||||
when (position) {
|
||||
TrackerTab.APPS.position -> {
|
||||
(holder as ListsTabViewHolder.AppsListViewHolder).onBind(uiState)
|
||||
}
|
||||
TrackerTab.TRACKERS.position -> {
|
||||
(holder as ListsTabViewHolder.TrackersListViewHolder).onBind(uiState.trackers ?: emptyList())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sealed class ListsTabViewHolder(view: View) : RecyclerView.ViewHolder(view) {
|
||||
protected fun setupRecyclerView(recyclerView: RecyclerView) {
|
||||
recyclerView.apply {
|
||||
layoutManager = LinearLayoutManager(context)
|
||||
setHasFixedSize(true)
|
||||
isNestedScrollingEnabled = false
|
||||
addItemDecoration(
|
||||
MaterialDividerItemDecoration(context, LinearLayoutManager.VERTICAL).apply {
|
||||
dividerColor = ContextCompat.getColor(context, R.color.divider)
|
||||
dividerInsetStart = 16.dpToPx(context)
|
||||
dividerInsetEnd = 16.dpToPx(context)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
class AppsListViewHolder(
|
||||
private val binding: TrackersAppsListBinding,
|
||||
private val onClickApp: (DisplayableApp) -> Unit,
|
||||
private val onToggleHideNoTrackersApps: () -> Unit
|
||||
) : ListsTabViewHolder(binding.root) {
|
||||
private val adapter = object : BindingListAdapter<TrackersItemAppBinding, AppWithCount>() {
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder<TrackersItemAppBinding> {
|
||||
return BindingViewHolder(
|
||||
TrackersItemAppBinding.inflate(
|
||||
LayoutInflater.from(parent.context),
|
||||
parent,
|
||||
false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: BindingViewHolder<TrackersItemAppBinding>, position: Int) {
|
||||
val item = dataSet[position]
|
||||
holder.binding.icon.setImageDrawable(item.app.icon)
|
||||
holder.binding.title.text = item.app.label
|
||||
holder.binding.counts.text = itemView.context.getString(
|
||||
R.string.trackers_list_app_trackers_counts, item.count.toString()
|
||||
)
|
||||
holder.binding.root.setOnClickListener {
|
||||
onClickApp(item.app)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setupRecyclerView(binding.list)
|
||||
binding.list.adapter = adapter
|
||||
binding.toggleNoTrackerApps.setOnClickListener { onToggleHideNoTrackersApps() }
|
||||
}
|
||||
|
||||
fun onBind(uiState: TrackersPeriodState) {
|
||||
adapter.dataSet = (
|
||||
if (uiState.hideNoTrackersApps) {
|
||||
uiState.appsWithTrackers
|
||||
} else {
|
||||
uiState.allApps
|
||||
}
|
||||
) ?: emptyList()
|
||||
|
||||
binding.toggleNoTrackerApps.apply {
|
||||
isCloseIconVisible = uiState.hideNoTrackersApps
|
||||
isChecked = uiState.hideNoTrackersApps
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TrackersListViewHolder(
|
||||
binding: TrackersListBinding,
|
||||
private val onClickTracker: (Tracker) -> Unit
|
||||
) : ListsTabViewHolder(binding.root) {
|
||||
|
||||
private val adapter = object : BindingListAdapter<TrackersItemAppBinding, TrackerWithCount>() {
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder<TrackersItemAppBinding> {
|
||||
return BindingViewHolder(
|
||||
TrackersItemAppBinding.inflate(
|
||||
LayoutInflater.from(parent.context),
|
||||
parent,
|
||||
false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: BindingViewHolder<TrackersItemAppBinding>, position: Int) {
|
||||
val item = dataSet[position]
|
||||
holder.binding.icon.isVisible = false
|
||||
holder.binding.title.text = item.tracker.label
|
||||
holder.binding.counts.text = itemView.context.getString(
|
||||
R.string.trackers_list_tracker_apps_counts, item.count.toString()
|
||||
)
|
||||
holder.binding.root.setOnClickListener { onClickTracker(item.tracker) }
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setupRecyclerView(binding.list)
|
||||
binding.list.adapter = adapter
|
||||
}
|
||||
|
||||
fun onBind(trackers: List<TrackerWithCount>) {
|
||||
adapter.dataSet = trackers
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.content.Context
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.ClickableSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.UnderlineSpan
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import androidx.core.content.ContextCompat
|
||||
import foundation.e.advancedprivacy.R
|
||||
|
||||
const val URL_LEARN_MORE_ABOUT_TRACKERS = "https://doc.e.foundation/support-topics/advanced_privacy#trackers-blocker"
|
||||
|
||||
fun setupDisclaimerBlock(view: TextView, onClickLearnMore: () -> Unit) {
|
||||
with(view) {
|
||||
linksClickable = true
|
||||
isClickable = true
|
||||
movementMethod = android.text.method.LinkMovementMethod.getInstance()
|
||||
text = buildSpan(view.context, onClickLearnMore)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSpan(context: Context, onClickLearnMore: () -> Unit): SpannableString {
|
||||
val start = context.getString(R.string.trackercontroldisclaimer_start)
|
||||
val body = context.getString(R.string.trackercontroldisclaimer_body)
|
||||
val link = context.getString(R.string.trackercontroldisclaimer_link)
|
||||
|
||||
val spannable = SpannableString("$start $body $link")
|
||||
|
||||
val startEndIndex = start.length + 1
|
||||
val linkStartIndex = startEndIndex + body.length + 1
|
||||
val linkEndIndex = spannable.length
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(ContextCompat.getColor(context, R.color.primary_text)),
|
||||
0,
|
||||
startEndIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(ContextCompat.getColor(context, R.color.disabled)),
|
||||
startEndIndex,
|
||||
linkStartIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(ContextCompat.getColor(context, R.color.accent)),
|
||||
linkStartIndex,
|
||||
linkEndIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
spannable.setSpan(UnderlineSpan(), linkStartIndex, linkEndIndex, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
|
||||
spannable.setSpan(
|
||||
object : ClickableSpan() {
|
||||
override fun onClick(p0: View) {
|
||||
onClickLearnMore.invoke()
|
||||
}
|
||||
},
|
||||
linkStartIndex,
|
||||
linkEndIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
return spannable
|
||||
}
|
|
@ -0,0 +1,171 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.method.LinkMovementMethod
|
||||
import android.text.style.ClickableSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.UnderlineSpan
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import com.google.android.material.tabs.TabLayoutMediator
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.common.extensions.findViewHolderForAdapterPosition
|
||||
import foundation.e.advancedprivacy.common.extensions.updatePagerHeightForChild
|
||||
import foundation.e.advancedprivacy.databinding.FragmentTrackersBinding
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
|
||||
class TrackersFragment : NavToolbarFragment(R.layout.fragment_trackers) {
|
||||
private val viewModel: TrackersViewModel by viewModel()
|
||||
private lateinit var binding: FragmentTrackersBinding
|
||||
|
||||
private lateinit var pagerAdapter: TrackersPeriodAdapter
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
binding = FragmentTrackersBinding.bind(view)
|
||||
|
||||
val trackersTabs = binding.trackersPeriodsTabs
|
||||
val trackersPager = binding.trackersPeriodsPager
|
||||
|
||||
pagerAdapter = TrackersPeriodAdapter(this, viewModel)
|
||||
trackersPager.adapter = pagerAdapter
|
||||
TabLayoutMediator(trackersTabs, trackersPager) { tab, position ->
|
||||
tab.text = getString(viewModel.getDisplayDuration(position))
|
||||
}.attach()
|
||||
|
||||
setupTrackersInfos()
|
||||
|
||||
binding.trackersPeriodsPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
|
||||
override fun onPageScrollStateChanged(state: Int) {
|
||||
super.onPageScrollStateChanged(state)
|
||||
if (state == ViewPager2.SCROLL_STATE_IDLE) {
|
||||
viewModel.onDisplayedItemChanged(binding.trackersPeriodsPager.currentItem)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
listenViewModel()
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
lifecycleScope.launch {
|
||||
binding.trackersPeriodsPager.currentItem = viewModel.getLastPosition()
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshUiHeight(): SharedFlow<Unit> {
|
||||
return viewModel.refreshUiHeight
|
||||
}
|
||||
|
||||
private fun listenViewModel() {
|
||||
with(viewLifecycleOwner) {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect(::handleEvents)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.navigate.collect(findNavController()::navigate)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleEvents(event: TrackersViewModel.SingleEvent) {
|
||||
when (event) {
|
||||
is TrackersViewModel.SingleEvent.ErrorEvent -> {
|
||||
displayToast(event.error)
|
||||
}
|
||||
is TrackersViewModel.SingleEvent.OpenUrl -> {
|
||||
try {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, event.url))
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
R.string.error_no_activity_view_url,
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setupTrackersInfos() {
|
||||
val infoText = getString(R.string.trackers_info)
|
||||
val moreText = getString(R.string.trackers_info_more)
|
||||
|
||||
val spannable = SpannableString("$infoText $moreText")
|
||||
val startIndex = infoText.length + 1
|
||||
val endIndex = spannable.length
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(ContextCompat.getColor(requireContext(), R.color.accent)),
|
||||
startIndex,
|
||||
endIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
spannable.setSpan(UnderlineSpan(), startIndex, endIndex, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
|
||||
spannable.setSpan(
|
||||
object : ClickableSpan() {
|
||||
override fun onClick(p0: View) {
|
||||
viewModel.onClickLearnMore()
|
||||
}
|
||||
},
|
||||
startIndex,
|
||||
endIndex,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
|
||||
with(binding.trackersInfo) {
|
||||
linksClickable = true
|
||||
isClickable = true
|
||||
movementMethod = LinkMovementMethod.getInstance()
|
||||
text = spannable
|
||||
}
|
||||
}
|
||||
|
||||
fun updatePagerHeight() {
|
||||
binding.trackersPeriodsPager.findViewHolderForAdapterPosition(binding.trackersPeriodsPager.currentItem)
|
||||
.let { currentViewHolder ->
|
||||
currentViewHolder?.itemView?.let { binding.trackersPeriodsPager.updatePagerHeightForChild(it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.viewpager2.adapter.FragmentStateAdapter
|
||||
|
||||
class TrackersPeriodAdapter(
|
||||
context: Fragment,
|
||||
private val viewModel: TrackersViewModel
|
||||
) : FragmentStateAdapter(context) {
|
||||
|
||||
override fun getItemCount(): Int {
|
||||
return viewModel.positionsCount
|
||||
}
|
||||
|
||||
override fun createFragment(position: Int): Fragment {
|
||||
return TrackersPeriodFragment().apply {
|
||||
arguments = TrackersPeriodFragment.buildArguments(period = viewModel.getPeriod(position))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,199 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import androidx.viewpager2.widget.ViewPager2
|
||||
import com.google.android.material.tabs.TabLayoutMediator
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.extensions.findViewHolderForAdapterPosition
|
||||
import foundation.e.advancedprivacy.common.extensions.updatePagerHeightForChild
|
||||
import foundation.e.advancedprivacy.databinding.TrackersPeriodFragmentBinding
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackersPeriodViewModel.SingleEvent
|
||||
import foundation.e.advancedprivacy.features.trackers.graph.GraphHolder
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import org.koin.core.parameter.parametersOf
|
||||
|
||||
class TrackersPeriodFragment : Fragment(R.layout.trackers_period_fragment) {
|
||||
|
||||
companion object {
|
||||
private const val ARG_PERIOD = "period"
|
||||
|
||||
fun buildArguments(period: Period): Bundle {
|
||||
return Bundle().apply {
|
||||
putString(ARG_PERIOD, period.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val viewModel: TrackersPeriodViewModel by viewModel {
|
||||
parametersOf(
|
||||
requireArguments().getString(
|
||||
ARG_PERIOD
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private val trackersFragment: TrackersFragment?
|
||||
get() = parentFragment as? TrackersFragment?
|
||||
|
||||
private lateinit var binding: TrackersPeriodFragmentBinding
|
||||
|
||||
private lateinit var tabAdapter: ListsTabPagerAdapter
|
||||
private lateinit var graphHolder: GraphHolder
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
|
||||
binding = TrackersPeriodFragmentBinding.bind(view)
|
||||
|
||||
graphHolder = GraphHolder(binding.graphContainer)
|
||||
|
||||
tabAdapter = ListsTabPagerAdapter(
|
||||
onClickApp = viewModel::onClickApp,
|
||||
onClickTracker = viewModel::onClickTracker,
|
||||
onToggleHideNoTrackersApps = viewModel::onToggleHideNoTrackersApps
|
||||
)
|
||||
binding.listsPager.adapter = tabAdapter
|
||||
|
||||
TabLayoutMediator(binding.listsTabs, binding.listsPager) { tab, position ->
|
||||
tab.text = getString(
|
||||
when (position) {
|
||||
TrackerTab.APPS.position -> R.string.trackers_toggle_list_apps
|
||||
else -> R.string.trackers_toggle_list_trackers
|
||||
}
|
||||
)
|
||||
}.attach()
|
||||
|
||||
binding.listsPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
|
||||
override fun onPageScrollStateChanged(state: Int) {
|
||||
super.onPageScrollStateChanged(state)
|
||||
if (state == ViewPager2.SCROLL_STATE_IDLE) {
|
||||
viewModel.onDisplayedItemChanged()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
listenViewModel()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
lifecycleScope.launch {
|
||||
viewModel.getStartPosition()?.let {
|
||||
binding.listsPager.currentItem = it
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
private fun listenViewModel() {
|
||||
with(viewLifecycleOwner) {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect(::handleEvents)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.RESUMED) {
|
||||
trackersFragment?.refreshUiHeight()?.let { parentFlow ->
|
||||
merge(
|
||||
parentFlow,
|
||||
viewModel.refreshUiHeight
|
||||
)
|
||||
.debounce(50)
|
||||
.collect { updatePagerHeight() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.navigate.collect(findNavController()::navigate)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleEvents(event: SingleEvent) {
|
||||
when (event) {
|
||||
is SingleEvent.ErrorEvent -> {
|
||||
displayToast(event.error)
|
||||
}
|
||||
is SingleEvent.OpenUrl -> {
|
||||
try {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, event.url))
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
R.string.error_no_activity_view_url,
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updatePagerHeight() {
|
||||
binding.listsPager.findViewHolderForAdapterPosition(binding.listsPager.currentItem)
|
||||
.let { currentViewHolder ->
|
||||
currentViewHolder?.itemView?.let { binding.listsPager.updatePagerHeightForChild(it) }
|
||||
}
|
||||
|
||||
trackersFragment?.updatePagerHeight()
|
||||
}
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun render(state: TrackersPeriodState) {
|
||||
graphHolder.onBind(state)
|
||||
tabAdapter.updateDataSet(state)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavDirections
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersAndAppsListsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersScreenUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class TrackersPeriodViewModel(
|
||||
private val period: Period,
|
||||
private val trackersStatisticsUseCase: TrackersStatisticsUseCase,
|
||||
private val trackersAndAppsListsUseCase: TrackersAndAppsListsUseCase,
|
||||
private val trackersScreenUseCase: TrackersScreenUseCase
|
||||
) : ViewModel() {
|
||||
|
||||
private val _state = MutableStateFlow(
|
||||
TrackersPeriodState(
|
||||
title = when (period) {
|
||||
Period.DAY -> R.string.trackers_graph_title_day
|
||||
Period.MONTH -> R.string.trackers_graph_title_month
|
||||
Period.YEAR -> R.string.trackers_graph_title_year
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
private val _refreshUiHeight = MutableSharedFlow<Unit>()
|
||||
val refreshUiHeight = _refreshUiHeight.asSharedFlow()
|
||||
|
||||
private val _navigate = MutableSharedFlow<NavDirections>()
|
||||
val navigate = _navigate.asSharedFlow()
|
||||
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
|
||||
trackersStatisticsUseCase.listenUpdates().collect {
|
||||
trackersStatisticsUseCase.getGraphData(period).let { graphData ->
|
||||
_state.update {
|
||||
it.copy(
|
||||
callsBlockedNLeaked = graphData.callsBlockedNLeaked,
|
||||
periods = graphData.periods,
|
||||
trackersCount = graphData.trackersCount,
|
||||
trackersAllowedCount = graphData.trackersAllowedCount,
|
||||
graduations = graphData.graduations
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
trackersAndAppsListsUseCase.getAppsAndTrackersCounts(period).let { lists ->
|
||||
_state.update {
|
||||
it.copy(
|
||||
trackers = lists.trackers,
|
||||
allApps = lists.allApps,
|
||||
appsWithTrackers = lists.appsWithTrackers
|
||||
)
|
||||
}
|
||||
_refreshUiHeight.emit(Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onClickTracker(tracker: Tracker) = viewModelScope.launch {
|
||||
_navigate.emit(TrackersFragmentDirections.gotoTrackerDetailsFragment(trackerId = tracker.id))
|
||||
}
|
||||
|
||||
fun onClickApp(app: DisplayableApp) = viewModelScope.launch {
|
||||
_navigate.emit(TrackersFragmentDirections.gotoAppTrackersFragment(appId = app.id))
|
||||
}
|
||||
|
||||
fun onToggleHideNoTrackersApps() = viewModelScope.launch {
|
||||
_state.update { it.copy(hideNoTrackersApps = !it.hideNoTrackersApps) }
|
||||
_refreshUiHeight.emit(Unit)
|
||||
}
|
||||
|
||||
fun onDisplayedItemChanged() = viewModelScope.launch {
|
||||
_refreshUiHeight.emit(Unit)
|
||||
}
|
||||
|
||||
fun getStartPosition(): Int? {
|
||||
val startPosition = trackersScreenUseCase.getTrackerTabStartPosition()
|
||||
return startPosition.takeIf { it in 0..1 }
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ErrorEvent(val error: String) : SingleEvent()
|
||||
data class OpenUrl(val url: Uri) : SingleEvent()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
* Copyright (C) 2023 - 2024 MURENA SAS
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.entities.AppWithCount
|
||||
import foundation.e.advancedprivacy.domain.entities.TrackerWithCount
|
||||
import java.time.Instant
|
||||
import java.time.ZonedDateTime
|
||||
import java.time.temporal.ChronoUnit
|
||||
import java.time.temporal.TemporalUnit
|
||||
|
||||
data class TrackersPeriodState(
|
||||
@StringRes val tabLabel: Int = R.string.empty,
|
||||
@StringRes val title: Int = R.string.empty,
|
||||
val callsBlockedNLeaked: List<Pair<Int, Int>> = emptyList(),
|
||||
val periods: List<String> = emptyList(),
|
||||
val trackersCount: Int = 0,
|
||||
val trackersAllowedCount: Int = 0,
|
||||
val graduations: List<String?>? = null,
|
||||
val allApps: List<AppWithCount>? = null,
|
||||
val trackers: List<TrackerWithCount>? = null,
|
||||
val appsWithTrackers: List<AppWithCount>? = null,
|
||||
val hideNoTrackersApps: Boolean = false
|
||||
) {
|
||||
|
||||
fun isEmptyCalls(): Boolean {
|
||||
return callsBlockedNLeaked.isEmpty() ||
|
||||
callsBlockedNLeaked.all { it.first == 0 && it.second == 0 }
|
||||
}
|
||||
}
|
||||
|
||||
enum class TrackerTab(val position: Int) {
|
||||
APPS(0),
|
||||
TRACKERS(1)
|
||||
}
|
||||
|
||||
enum class Period(val periodsCount: Int, val periodUnit: TemporalUnit) {
|
||||
DAY(24, ChronoUnit.HOURS),
|
||||
MONTH(30, ChronoUnit.DAYS),
|
||||
YEAR(12, ChronoUnit.MONTHS);
|
||||
|
||||
fun getPeriodStart(): Instant {
|
||||
var start = ZonedDateTime.now()
|
||||
.minus(periodsCount.toLong(), periodUnit)
|
||||
.plus(1, periodUnit)
|
||||
var truncatePeriodUnit = periodUnit
|
||||
if (periodUnit === ChronoUnit.MONTHS) {
|
||||
start = start.withDayOfMonth(1)
|
||||
truncatePeriodUnit = ChronoUnit.DAYS
|
||||
}
|
||||
|
||||
return start.truncatedTo(truncatePeriodUnit).toInstant()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.navigation.NavDirections
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersScreenUseCase
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class TrackersViewModel(private val trackersScreenUseCase: TrackersScreenUseCase) : ViewModel() {
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
private val _navigate = MutableSharedFlow<NavDirections>()
|
||||
val navigate = _navigate.asSharedFlow()
|
||||
|
||||
private val _refreshUiHeight = MutableSharedFlow<Unit>()
|
||||
val refreshUiHeight = _refreshUiHeight.asSharedFlow()
|
||||
|
||||
val positionsCount = 3
|
||||
fun getPeriod(position: Int): Period {
|
||||
return when (position) {
|
||||
0 -> Period.DAY
|
||||
1 -> Period.MONTH
|
||||
2 -> Period.YEAR
|
||||
else -> Period.DAY
|
||||
}
|
||||
}
|
||||
|
||||
fun getDisplayDuration(position: Int): Int {
|
||||
return when (position) {
|
||||
0 -> R.string.trackers_period_day
|
||||
1 -> R.string.trackers_period_month
|
||||
else -> R.string.trackers_period_year
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getLastPosition(): Int {
|
||||
val lastPosition = trackersScreenUseCase.getLastPosition()
|
||||
return if (lastPosition in 0 until positionsCount) {
|
||||
lastPosition
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fun onDisplayedItemChanged(position: Int) = viewModelScope.launch(Dispatchers.IO) {
|
||||
trackersScreenUseCase.savePosition(position)
|
||||
trackersScreenUseCase.resetTrackerTabStartPosition()
|
||||
_refreshUiHeight.emit(Unit)
|
||||
}
|
||||
|
||||
fun onClickLearnMore() = viewModelScope.launch {
|
||||
_singleEvents.emit(SingleEvent.OpenUrl(Uri.parse(URL_LEARN_MORE_ABOUT_TRACKERS)))
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ErrorEvent(val error: String) : SingleEvent()
|
||||
data class OpenUrl(val url: Uri) : SingleEvent()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,180 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.apptrackers
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.navigation.fragment.navArgs
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.divider.MaterialDividerItemDecoration
|
||||
import com.google.android.material.snackbar.Snackbar
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.BigNumberFormatter
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.databinding.ApptrackersFragmentBinding
|
||||
import foundation.e.advancedprivacy.features.trackers.setupDisclaimerBlock
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import org.koin.core.parameter.parametersOf
|
||||
|
||||
class AppTrackersFragment : NavToolbarFragment(R.layout.apptrackers_fragment) {
|
||||
|
||||
private val args: AppTrackersFragmentArgs by navArgs()
|
||||
private val viewModel: AppTrackersViewModel by viewModel { parametersOf(args.appId) }
|
||||
|
||||
private val numberFormatter: BigNumberFormatter by lazy { BigNumberFormatter(requireContext()) }
|
||||
|
||||
private lateinit var binding: ApptrackersFragmentBinding
|
||||
|
||||
override fun getTitle(): CharSequence {
|
||||
return ""
|
||||
}
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
binding = ApptrackersFragmentBinding.bind(view)
|
||||
|
||||
binding.blockAllToggle.setOnClickListener {
|
||||
viewModel.onToggleBlockAll(binding.blockAllToggle.isChecked)
|
||||
}
|
||||
binding.btnReset.setOnClickListener { viewModel.onClickResetAllTrackers() }
|
||||
|
||||
binding.list.apply {
|
||||
layoutManager = LinearLayoutManager(requireContext())
|
||||
setHasFixedSize(true)
|
||||
addItemDecoration(
|
||||
MaterialDividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL).apply {
|
||||
dividerColor = ContextCompat.getColor(requireContext(), R.color.divider)
|
||||
}
|
||||
)
|
||||
adapter = ToggleTrackersAdapter(viewModel)
|
||||
}
|
||||
|
||||
listenViewModel()
|
||||
|
||||
setupDisclaimerBlock(binding.disclaimerBlockTrackers.root, viewModel::onClickLearnMore)
|
||||
}
|
||||
|
||||
private fun listenViewModel() {
|
||||
with(viewLifecycleOwner) {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect(::handleEvents)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun handleEvents(event: AppTrackersViewModel.SingleEvent) {
|
||||
when (event) {
|
||||
is AppTrackersViewModel.SingleEvent.ErrorEvent ->
|
||||
displayToast(getString(event.errorResId))
|
||||
|
||||
is AppTrackersViewModel.SingleEvent.OpenUrl ->
|
||||
try {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, event.url))
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
R.string.error_no_activity_view_url,
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
|
||||
is AppTrackersViewModel.SingleEvent.ToastTrackersControlDisabled ->
|
||||
Snackbar.make(
|
||||
binding.root,
|
||||
R.string.apptrackers_tracker_control_disabled_message,
|
||||
Snackbar.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun render(state: AppTrackersState) {
|
||||
setTitle(state.app?.label)
|
||||
binding.subtitle.text = getString(R.string.apptrackers_subtitle, state.app?.label)
|
||||
binding.dataDetectedTrackers.apply {
|
||||
primaryMessage.setText(R.string.apptrackers_detected_tracker_primary)
|
||||
number.text = state.getTrackersCount().toString()
|
||||
secondaryMessage.setText(R.string.apptrackers_detected_tracker_secondary)
|
||||
}
|
||||
|
||||
binding.dataBlockedTrackers.apply {
|
||||
primaryMessage.setText(R.string.apptrackers_blocked_tracker_primary)
|
||||
number.text = state.getBlockedTrackersCount().toString()
|
||||
secondaryMessage.setText(R.string.apptrackers_blocked_tracker_secondary)
|
||||
}
|
||||
|
||||
binding.dataBlockedLeaks.apply {
|
||||
primaryMessage.setText(R.string.apptrackers_blocked_leaks_primary)
|
||||
number.text = numberFormatter.format(state.blocked)
|
||||
secondaryMessage.text = getString(R.string.apptrackers_blocked_leaks_secondary, numberFormatter.format(state.leaked))
|
||||
}
|
||||
|
||||
binding.blockAllToggle.isChecked = state.isBlockingActivated
|
||||
|
||||
val trackersStatus = state.trackersWithBlockedList
|
||||
if (!trackersStatus.isEmpty()) {
|
||||
binding.listTitle.isVisible = true
|
||||
binding.list.isVisible = true
|
||||
binding.list.post {
|
||||
(binding.list.adapter as ToggleTrackersAdapter?)?.updateDataSet(trackersStatus)
|
||||
}
|
||||
binding.noTrackersYet.isVisible = false
|
||||
binding.btnReset.isVisible = true
|
||||
} else {
|
||||
binding.listTitle.isVisible = false
|
||||
binding.list.isVisible = false
|
||||
binding.noTrackersYet.isVisible = true
|
||||
binding.noTrackersYet.text = getString(
|
||||
when {
|
||||
!state.isBlockingActivated -> R.string.apptrackers_no_trackers_yet_block_off
|
||||
state.isWhitelistEmpty -> R.string.apptrackers_no_trackers_yet_block_on
|
||||
else -> R.string.app_trackers_no_trackers_yet_remaining_whitelist
|
||||
}
|
||||
)
|
||||
binding.btnReset.isVisible = state.isBlockingActivated && !state.isWhitelistEmpty
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.apptrackers
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
data class AppTrackersState(
|
||||
val app: DisplayableApp? = null,
|
||||
val isBlockingActivated: Boolean = false,
|
||||
val trackersWithBlockedList: List<Pair<Tracker, Boolean>> = emptyList(),
|
||||
val leaked: Int = 0,
|
||||
val blocked: Int = 0,
|
||||
val isTrackersBlockingEnabled: Boolean = false,
|
||||
val isWhitelistEmpty: Boolean = true
|
||||
) {
|
||||
fun getTrackersCount() = trackersWithBlockedList.size
|
||||
|
||||
fun getBlockedTrackersCount(): Int = trackersWithBlockedList.count { it.second }
|
||||
}
|
|
@ -0,0 +1,154 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.apptrackers
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.usecases.AppTrackersUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.features.trackers.URL_LEARN_MORE_ABOUT_TRACKERS
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class AppTrackersViewModel(
|
||||
private val app: DisplayableApp,
|
||||
private val appTrackersUseCase: AppTrackersUseCase,
|
||||
private val trackersStateUseCase: TrackersStateUseCase,
|
||||
private val trackersStatisticsUseCase: TrackersStatisticsUseCase,
|
||||
private val getQuickPrivacyStateUseCase: GetQuickPrivacyStateUseCase
|
||||
) : ViewModel() {
|
||||
private val _state = MutableStateFlow(AppTrackersState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
init {
|
||||
_state.update {
|
||||
it.copy(
|
||||
app = app
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
|
||||
merge(
|
||||
getQuickPrivacyStateUseCase.trackerMode.map {
|
||||
_state.update { s -> s.copy(isTrackersBlockingEnabled = it != FeatureMode.VULNERABLE) }
|
||||
},
|
||||
trackersStatisticsUseCase.listenUpdates().map { fetchStatistics() }
|
||||
).collect()
|
||||
}
|
||||
|
||||
fun onClickLearnMore() {
|
||||
viewModelScope.launch {
|
||||
_singleEvents.emit(SingleEvent.OpenUrl(Uri.parse(URL_LEARN_MORE_ABOUT_TRACKERS)))
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleBlockAll(isBlocked: Boolean) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
if (!state.value.isTrackersBlockingEnabled) {
|
||||
_singleEvents.emit(SingleEvent.ToastTrackersControlDisabled)
|
||||
}
|
||||
appTrackersUseCase.toggleAppWhitelist(
|
||||
app,
|
||||
state.value.trackersWithBlockedList.map { it.first },
|
||||
isBlocked
|
||||
)
|
||||
updateWhitelist()
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleTracker(tracker: Tracker, isBlocked: Boolean) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
if (!state.value.isTrackersBlockingEnabled) {
|
||||
_singleEvents.emit(SingleEvent.ToastTrackersControlDisabled)
|
||||
}
|
||||
|
||||
trackersStateUseCase.blockTracker(app, tracker, isBlocked)
|
||||
updateWhitelist()
|
||||
}
|
||||
}
|
||||
|
||||
fun onClickTracker(tracker: Tracker) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
tracker.link?.let {
|
||||
runCatching { Uri.parse(it) }.getOrNull()
|
||||
}?.let { _singleEvents.emit(SingleEvent.OpenUrl(it)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun onClickResetAllTrackers() {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
appTrackersUseCase.clearWhitelist(app)
|
||||
updateWhitelist()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun fetchStatistics() = withContext(Dispatchers.IO) {
|
||||
val (blocked, leaked) = appTrackersUseCase.getCalls(app)
|
||||
val trackersWithBlockedList = appTrackersUseCase.getTrackersWithBlockedList(app)
|
||||
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
leaked = leaked,
|
||||
blocked = blocked,
|
||||
isBlockingActivated = !trackersStateUseCase.isWhitelisted(app),
|
||||
isWhitelistEmpty = trackersStatisticsUseCase.isWhiteListEmpty(app),
|
||||
trackersWithBlockedList = trackersWithBlockedList
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun updateWhitelist() = withContext(Dispatchers.IO) {
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
isBlockingActivated = !trackersStateUseCase.isWhitelisted(app),
|
||||
trackersWithBlockedList = appTrackersUseCase.enrichWithBlockedState(
|
||||
app,
|
||||
s.trackersWithBlockedList.map { it.first }
|
||||
),
|
||||
isWhitelistEmpty = trackersStatisticsUseCase.isWhiteListEmpty(app)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ErrorEvent(@StringRes val errorResId: Int) : SingleEvent()
|
||||
data class OpenUrl(val url: Uri) : SingleEvent()
|
||||
object ToastTrackersControlDisabled : SingleEvent()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.apptrackers
|
||||
|
||||
import android.text.SpannableString
|
||||
import android.text.style.UnderlineSpan
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.databinding.ApptrackersItemTrackerToggleBinding
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
class ToggleTrackersAdapter(
|
||||
private val viewModel: AppTrackersViewModel
|
||||
) : RecyclerView.Adapter<ToggleTrackersAdapter.ViewHolder>() {
|
||||
class ViewHolder(
|
||||
private val binding: ApptrackersItemTrackerToggleBinding,
|
||||
private val viewModel: AppTrackersViewModel
|
||||
) : RecyclerView.ViewHolder(binding.root) {
|
||||
|
||||
fun bind(item: Pair<Tracker, Boolean>) {
|
||||
val label = item.first.label
|
||||
with(binding.title) {
|
||||
if (item.first.link != null) {
|
||||
setTextColor(ContextCompat.getColor(context, R.color.accent))
|
||||
val spannable = SpannableString(label)
|
||||
spannable.setSpan(UnderlineSpan(), 0, spannable.length, 0)
|
||||
text = spannable
|
||||
} else {
|
||||
setTextColor(ContextCompat.getColor(context, R.color.primary_text))
|
||||
text = label
|
||||
}
|
||||
setOnClickListener { viewModel.onClickTracker(item.first) }
|
||||
}
|
||||
with(binding.toggle) {
|
||||
isChecked = item.second
|
||||
|
||||
setOnClickListener {
|
||||
viewModel.onToggleTracker(item.first, isChecked)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var dataSet: List<Pair<Tracker, Boolean>> = emptyList()
|
||||
|
||||
fun updateDataSet(new: List<Pair<Tracker, Boolean>>) {
|
||||
dataSet = new
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
return ViewHolder(
|
||||
ApptrackersItemTrackerToggleBinding.inflate(
|
||||
LayoutInflater.from(parent.context),
|
||||
parent,
|
||||
false
|
||||
),
|
||||
viewModel
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
val permission = dataSet[position]
|
||||
holder.bind(permission)
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = dataSet.size
|
||||
}
|
|
@ -0,0 +1,299 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.graph
|
||||
|
||||
import android.graphics.Canvas
|
||||
import android.view.View
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.view.isVisible
|
||||
import com.github.mikephil.charting.components.AxisBase
|
||||
import com.github.mikephil.charting.components.XAxis
|
||||
import com.github.mikephil.charting.components.YAxis.AxisDependency
|
||||
import com.github.mikephil.charting.data.BarData
|
||||
import com.github.mikephil.charting.data.BarDataSet
|
||||
import com.github.mikephil.charting.data.BarEntry
|
||||
import com.github.mikephil.charting.data.Entry
|
||||
import com.github.mikephil.charting.formatter.ValueFormatter
|
||||
import com.github.mikephil.charting.highlight.Highlight
|
||||
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
|
||||
import com.github.mikephil.charting.renderer.XAxisRenderer
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.extensions.dpToPxF
|
||||
import foundation.e.advancedprivacy.databinding.TrackersItemGraphBinding
|
||||
import foundation.e.advancedprivacy.features.trackers.TrackersPeriodState
|
||||
import kotlin.math.floor
|
||||
|
||||
class GraphHolder(private val binding: TrackersItemGraphBinding) {
|
||||
|
||||
companion object {
|
||||
private const val x_axis_graduations_count_threshold = 24
|
||||
}
|
||||
|
||||
private val context = binding.root.context
|
||||
private val barChart = binding.graph
|
||||
|
||||
private val periodMarker = PeriodMarkerView(context)
|
||||
|
||||
private var data = emptyList<Pair<Int, Int>>()
|
||||
private var labels = emptyList<String>()
|
||||
private var graduations: List<String?> = emptyList()
|
||||
private val isHalfGraduations: Boolean
|
||||
get() = graduations.size > x_axis_graduations_count_threshold
|
||||
|
||||
private var isHighlighted = false
|
||||
|
||||
private val onChartValueSelectedListener = object : OnChartValueSelectedListener {
|
||||
override fun onValueSelected(e: Entry?, h: Highlight?) {
|
||||
h?.let {
|
||||
val index = it.x.toInt()
|
||||
if (index >= 0 &&
|
||||
index < labels.size &&
|
||||
index < data.size
|
||||
) {
|
||||
val period = labels[index]
|
||||
val (blocked, leaked) = data[index]
|
||||
periodMarker.setLabel(period, blocked, leaked)
|
||||
}
|
||||
}
|
||||
isHighlighted = true
|
||||
}
|
||||
|
||||
override fun onNothingSelected() {
|
||||
isHighlighted = false
|
||||
}
|
||||
}
|
||||
|
||||
private val xAxisRenderer = object : XAxisRenderer(
|
||||
barChart.viewPortHandler,
|
||||
barChart.xAxis,
|
||||
barChart.getTransformer(AxisDependency.LEFT)
|
||||
) {
|
||||
override fun renderAxisLine(c: Canvas) {
|
||||
mAxisLinePaint.color = mXAxis.axisLineColor
|
||||
mAxisLinePaint.strokeWidth = mXAxis.axisLineWidth
|
||||
mAxisLinePaint.pathEffect = mXAxis.axisLineDashPathEffect
|
||||
|
||||
// Bottom line
|
||||
c.drawLine(
|
||||
mViewPortHandler.contentLeft(),
|
||||
mViewPortHandler.contentBottom() - 5.dpToPxF(context),
|
||||
|
||||
mViewPortHandler.contentRight(),
|
||||
mViewPortHandler.contentBottom() - 5.dpToPxF(context),
|
||||
mAxisLinePaint
|
||||
)
|
||||
}
|
||||
|
||||
override fun renderGridLines(c: Canvas) {
|
||||
if (!mXAxis.isDrawGridLinesEnabled || !mXAxis.isEnabled) return
|
||||
val clipRestoreCount = c.save()
|
||||
c.clipRect(gridClippingRect)
|
||||
if (mRenderGridLinesBuffer.size != mAxis.mEntryCount * 2) {
|
||||
mRenderGridLinesBuffer = FloatArray(mXAxis.mEntryCount * 2)
|
||||
}
|
||||
|
||||
val positions = mRenderGridLinesBuffer
|
||||
mXAxis.mEntries.forEachIndexed { index, value ->
|
||||
if ((index * 2 + 1) < positions.size) {
|
||||
positions[index * 2] = value
|
||||
positions[index * 2 + 1] = value
|
||||
}
|
||||
}
|
||||
|
||||
mTrans.pointValuesToPixel(positions)
|
||||
|
||||
val graduationPositions = positions.filterIndexed { index, _ -> index % 2 == 0 }
|
||||
|
||||
setupGridPaint()
|
||||
val gridLinePath = mRenderGridLinesPath
|
||||
gridLinePath.reset()
|
||||
|
||||
graduationPositions.forEachIndexed { i, x ->
|
||||
|
||||
val graduationIndex = if (isHalfGraduations) 2 * i else i
|
||||
val hasLabel = graduations.getOrNull(graduationIndex) != null
|
||||
val bottomY = if (hasLabel) 0 else 3
|
||||
|
||||
gridLinePath.moveTo(x, mViewPortHandler.contentBottom() - 5.dpToPxF(context))
|
||||
gridLinePath.lineTo(x, mViewPortHandler.contentBottom() - bottomY.dpToPxF(context))
|
||||
|
||||
c.drawPath(gridLinePath, mGridPaint)
|
||||
|
||||
gridLinePath.reset()
|
||||
}
|
||||
c.restoreToCount(clipRestoreCount)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
with(barChart) {
|
||||
description = null
|
||||
setTouchEnabled(true)
|
||||
setScaleEnabled(false)
|
||||
|
||||
setDrawGridBackground(false)
|
||||
setDrawBorders(false)
|
||||
axisLeft.isEnabled = false
|
||||
axisRight.isEnabled = false
|
||||
|
||||
legend.isEnabled = false
|
||||
|
||||
extraTopOffset = 40f
|
||||
extraBottomOffset = 4f
|
||||
|
||||
extraLeftOffset = 16f
|
||||
extraRightOffset = 16f
|
||||
|
||||
offsetTopAndBottom(0)
|
||||
|
||||
minOffset = 0f
|
||||
|
||||
offsetTopAndBottom(0)
|
||||
|
||||
setDrawValueAboveBar(false)
|
||||
|
||||
periodMarker.chartView = barChart
|
||||
|
||||
marker = periodMarker
|
||||
|
||||
setOnChartValueSelectedListener(onChartValueSelectedListener)
|
||||
|
||||
setXAxisRenderer(xAxisRenderer)
|
||||
}
|
||||
}
|
||||
|
||||
fun onBind(state: TrackersPeriodState) {
|
||||
with(binding) {
|
||||
title.text = context.getString(state.title)
|
||||
val views = listOf(
|
||||
helperText,
|
||||
legendBlockedIcon,
|
||||
legendBlocked,
|
||||
legendAllowedIcon,
|
||||
legendAllowed,
|
||||
trackersDetected,
|
||||
trackersAllowed
|
||||
)
|
||||
|
||||
if (state.isEmptyCalls()) {
|
||||
graph.visibility = View.INVISIBLE
|
||||
graphEmpty.isVisible = true
|
||||
views.forEach { it.isVisible = false }
|
||||
} else {
|
||||
graph.isVisible = true
|
||||
graphEmpty.isVisible = false
|
||||
views.forEach { it.isVisible = true }
|
||||
trackersDetected.text = context.getString(
|
||||
R.string.trackers_graph_detected_trackers,
|
||||
state.trackersCount
|
||||
)
|
||||
trackersAllowed.text = context.getString(
|
||||
R.string.trackers_graph_allowed_trackers,
|
||||
state.trackersAllowedCount
|
||||
)
|
||||
|
||||
refreshDataSet(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshDataSet(state: TrackersPeriodState) {
|
||||
data = state.callsBlockedNLeaked
|
||||
labels = state.periods
|
||||
graduations = state.graduations ?: emptyList()
|
||||
|
||||
val trackersDataSet = BarDataSet(
|
||||
data.mapIndexed { index, value ->
|
||||
BarEntry(
|
||||
index.toFloat(),
|
||||
floatArrayOf(value.first.toFloat(), value.second.toFloat())
|
||||
)
|
||||
},
|
||||
""
|
||||
)
|
||||
|
||||
val blockedColor = ContextCompat.getColor(context, R.color.switch_track_on)
|
||||
val leakedColor = ContextCompat.getColor(context, R.color.red_off)
|
||||
|
||||
trackersDataSet.colors = listOf(
|
||||
blockedColor,
|
||||
leakedColor
|
||||
)
|
||||
trackersDataSet.setDrawValues(false)
|
||||
|
||||
barChart.data = BarData(trackersDataSet)
|
||||
prepareYAxis()
|
||||
prepareXAxis()
|
||||
|
||||
barChart.invalidate()
|
||||
}
|
||||
|
||||
private fun prepareYAxis() {
|
||||
val maxValue = data.maxOfOrNull { it.first + it.second } ?: 0
|
||||
|
||||
barChart.axisLeft.apply {
|
||||
isEnabled = true
|
||||
|
||||
setDrawGridLines(false)
|
||||
setDrawLabels(true)
|
||||
setCenterAxisLabels(false)
|
||||
setLabelCount(2, true)
|
||||
textColor = context.getColor(R.color.primary_text)
|
||||
valueFormatter = object : ValueFormatter() {
|
||||
override fun getAxisLabel(value: Float, axis: AxisBase?): String {
|
||||
return if (value >= maxValue.toFloat()) maxValue.toString() else ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val xAxisValueFormatter = object : ValueFormatter() {
|
||||
override fun getAxisLabel(value: Float, axis: AxisBase?): String {
|
||||
val index = floor(value).toInt() + 1
|
||||
return graduations.getOrNull(index) ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
private val halfGraduationsXAxisValueFormatter = object : ValueFormatter() {
|
||||
override fun getAxisLabel(value: Float, axis: AxisBase?): String {
|
||||
val index = floor(value).toInt() + 1
|
||||
return graduations.getOrNull(index) ?: graduations.getOrNull(index + 1) ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
private fun prepareXAxis() {
|
||||
barChart.xAxis.apply {
|
||||
isEnabled = true
|
||||
position = XAxis.XAxisPosition.BOTTOM
|
||||
|
||||
setDrawGridLines(true)
|
||||
setDrawLabels(true)
|
||||
setCenterAxisLabels(false)
|
||||
textColor = context.getColor(R.color.primary_text)
|
||||
|
||||
// setLabelCount can't have more than 25 labels.
|
||||
if (isHalfGraduations) {
|
||||
setLabelCount((graduations.size / 2) + 1, true)
|
||||
valueFormatter = halfGraduationsXAxisValueFormatter
|
||||
} else {
|
||||
setLabelCount(graduations.size + 1, true)
|
||||
valueFormatter = xAxisValueFormatter
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,124 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.graph
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.DynamicDrawableSpan
|
||||
import android.text.style.ImageSpan
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import androidx.core.text.toSpannable
|
||||
import androidx.core.view.isVisible
|
||||
import com.github.mikephil.charting.components.MarkerView
|
||||
import com.github.mikephil.charting.data.Entry
|
||||
import com.github.mikephil.charting.highlight.Highlight
|
||||
import com.github.mikephil.charting.utils.MPPointF
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.extensions.dpToPxF
|
||||
|
||||
class PeriodMarkerView(context: Context) : MarkerView(context, R.layout.chart_tooltip) {
|
||||
enum class ArrowPosition { LEFT, CENTER, RIGHT }
|
||||
|
||||
private val arrowMargins = 10.dpToPxF(context)
|
||||
private val mOffset2 = MPPointF(0f, 0f)
|
||||
|
||||
private fun getArrowPosition(posX: Float): ArrowPosition {
|
||||
val halfWidth = width / 2
|
||||
|
||||
return chartView?.let { chart ->
|
||||
if (posX < halfWidth) {
|
||||
ArrowPosition.LEFT
|
||||
} else if (chart.width - posX < halfWidth) {
|
||||
ArrowPosition.RIGHT
|
||||
} else {
|
||||
ArrowPosition.CENTER
|
||||
}
|
||||
} ?: ArrowPosition.CENTER
|
||||
}
|
||||
|
||||
private fun showArrow(position: ArrowPosition?) {
|
||||
val ids = listOf(
|
||||
R.id.arrow_bottom_left,
|
||||
R.id.arrow_bottom_center,
|
||||
R.id.arrow_bottom_right
|
||||
)
|
||||
|
||||
val toShow = when (position) {
|
||||
ArrowPosition.LEFT -> R.id.arrow_bottom_left
|
||||
ArrowPosition.CENTER -> R.id.arrow_bottom_center
|
||||
ArrowPosition.RIGHT -> R.id.arrow_bottom_right
|
||||
else -> null
|
||||
}
|
||||
|
||||
ids.forEach { id ->
|
||||
val showIt = id == toShow
|
||||
findViewById<View>(id)?.let {
|
||||
if (it.isVisible != showIt) {
|
||||
it.isVisible = showIt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setLabel(period: String, blocked: Int, leaked: Int) {
|
||||
val span = SpannableStringBuilder(period)
|
||||
span.append(" | ")
|
||||
span.setSpan(
|
||||
ImageSpan(context, R.drawable.ic_legend_blocked, DynamicDrawableSpan.ALIGN_BASELINE),
|
||||
span.length - 1,
|
||||
span.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
span.append(" $blocked ")
|
||||
span.setSpan(
|
||||
ImageSpan(context, R.drawable.ic_legend_leaked, DynamicDrawableSpan.ALIGN_BASELINE),
|
||||
span.length - 1,
|
||||
span.length,
|
||||
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
span.append(" $leaked")
|
||||
findViewById<TextView>(R.id.label).text = span.toSpannable()
|
||||
}
|
||||
|
||||
override fun refreshContent(e: Entry?, highlight: Highlight?) {
|
||||
highlight?.let {
|
||||
showArrow(getArrowPosition(highlight.xPx))
|
||||
}
|
||||
super.refreshContent(e, highlight)
|
||||
}
|
||||
|
||||
override fun getOffsetForDrawingAtPoint(posX: Float, posY: Float): MPPointF {
|
||||
val x = when (getArrowPosition(posX)) {
|
||||
ArrowPosition.LEFT -> -arrowMargins
|
||||
ArrowPosition.RIGHT -> -width + arrowMargins
|
||||
ArrowPosition.CENTER -> -width.toFloat() / 2
|
||||
}
|
||||
|
||||
mOffset2.x = x
|
||||
mOffset2.y = -posY
|
||||
|
||||
return mOffset2
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas?, posX: Float, posY: Float) {
|
||||
super.draw(canvas, posX, posY)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.trackerdetails
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import foundation.e.advancedprivacy.databinding.ApptrackersItemTrackerToggleBinding
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
|
||||
class TrackerAppsAdapter(
|
||||
private val viewModel: TrackerDetailsViewModel
|
||||
) : RecyclerView.Adapter<TrackerAppsAdapter.ViewHolder>() {
|
||||
|
||||
class ViewHolder(
|
||||
private val binding: ApptrackersItemTrackerToggleBinding,
|
||||
private val viewModel: TrackerDetailsViewModel
|
||||
) : RecyclerView.ViewHolder(binding.root) {
|
||||
|
||||
fun bind(item: ToggleableApp) {
|
||||
binding.title.text = item.app.label
|
||||
binding.toggle.apply {
|
||||
this.isChecked = item.isOn
|
||||
setOnClickListener {
|
||||
viewModel.onToggleUnblockApp(item.app, isChecked)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var dataSet: List<ToggleableApp> = emptyList()
|
||||
|
||||
fun updateDataSet(new: List<ToggleableApp>) {
|
||||
dataSet = new
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
|
||||
return ViewHolder(
|
||||
ApptrackersItemTrackerToggleBinding.inflate(LayoutInflater.from(parent.context), parent, false),
|
||||
viewModel
|
||||
)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
|
||||
holder.bind(dataSet[position])
|
||||
}
|
||||
|
||||
override fun getItemCount(): Int = dataSet.size
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.trackerdetails
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.core.content.ContextCompat.getColor
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.navigation.fragment.navArgs
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.divider.MaterialDividerItemDecoration
|
||||
import com.google.android.material.snackbar.Snackbar
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.common.BigNumberFormatter
|
||||
import foundation.e.advancedprivacy.common.NavToolbarFragment
|
||||
import foundation.e.advancedprivacy.databinding.TrackerdetailsFragmentBinding
|
||||
import foundation.e.advancedprivacy.features.trackers.setupDisclaimerBlock
|
||||
import kotlinx.coroutines.launch
|
||||
import org.koin.androidx.viewmodel.ext.android.viewModel
|
||||
import org.koin.core.parameter.parametersOf
|
||||
|
||||
class TrackerDetailsFragment : NavToolbarFragment(R.layout.trackerdetails_fragment) {
|
||||
|
||||
private val args: TrackerDetailsFragmentArgs by navArgs()
|
||||
private val viewModel: TrackerDetailsViewModel by viewModel { parametersOf(args.trackerId) }
|
||||
private val numberFormatter: BigNumberFormatter by lazy { BigNumberFormatter(requireContext()) }
|
||||
|
||||
private lateinit var binding: TrackerdetailsFragmentBinding
|
||||
|
||||
override fun getTitle(): CharSequence {
|
||||
return ""
|
||||
}
|
||||
|
||||
private fun displayToast(message: String) {
|
||||
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT)
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
binding = TrackerdetailsFragmentBinding.bind(view)
|
||||
|
||||
binding.blockAllToggle.setOnClickListener {
|
||||
viewModel.onToggleBlockAll(binding.blockAllToggle.isChecked)
|
||||
}
|
||||
|
||||
binding.apps.apply {
|
||||
layoutManager = LinearLayoutManager(requireContext())
|
||||
setHasFixedSize(true)
|
||||
addItemDecoration(
|
||||
MaterialDividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL).apply {
|
||||
dividerColor = getColor(requireContext(), R.color.divider)
|
||||
}
|
||||
)
|
||||
adapter = TrackerAppsAdapter(viewModel)
|
||||
}
|
||||
|
||||
setupDisclaimerBlock(binding.disclaimerBlockTrackers.root, viewModel::onClickLearnMore)
|
||||
|
||||
listenViewModel()
|
||||
}
|
||||
|
||||
private fun listenViewModel() {
|
||||
with(viewLifecycleOwner) {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.singleEvents.collect(::handleEvents)
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
viewModel.doOnStartedState()
|
||||
}
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
render(viewModel.state.value)
|
||||
viewModel.state.collect(::render)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleEvents(event: TrackerDetailsViewModel.SingleEvent) {
|
||||
when (event) {
|
||||
is TrackerDetailsViewModel.SingleEvent.ErrorEvent ->
|
||||
displayToast(getString(event.errorResId))
|
||||
is TrackerDetailsViewModel.SingleEvent.ToastTrackersControlDisabled ->
|
||||
Snackbar.make(
|
||||
binding.root,
|
||||
R.string.apptrackers_tracker_control_disabled_message,
|
||||
Snackbar.LENGTH_LONG
|
||||
).show()
|
||||
is TrackerDetailsViewModel.SingleEvent.OpenUrl -> {
|
||||
try {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, event.url))
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Toast.makeText(
|
||||
requireContext(),
|
||||
R.string.error_no_activity_view_url,
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun render(state: TrackerDetailsState) {
|
||||
setTitle(state.tracker?.label)
|
||||
binding.subtitle.text = getString(R.string.trackerdetails_subtitle, state.tracker?.label)
|
||||
binding.dataAppCount.apply {
|
||||
primaryMessage.setText(R.string.trackerdetails_app_count_primary)
|
||||
number.text = state.detectedCount.toString()
|
||||
secondaryMessage.setText(R.string.trackerdetails_app_count_secondary)
|
||||
}
|
||||
|
||||
binding.dataBlockedLeaks.apply {
|
||||
primaryMessage.setText(R.string.trackerdetails_blocked_leaks_primary)
|
||||
number.text = numberFormatter.format(state.blockedCount)
|
||||
secondaryMessage.text = getString(R.string.trackerdetails_blocked_leaks_secondary, numberFormatter.format(state.leakedCount))
|
||||
}
|
||||
|
||||
binding.blockAllToggle.isChecked = state.isBlockAllActivated
|
||||
|
||||
binding.apps.post {
|
||||
(binding.apps.adapter as TrackerAppsAdapter?)?.updateDataSet(state.appList)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.trackerdetails
|
||||
|
||||
import foundation.e.advancedprivacy.domain.entities.ToggleableApp
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
|
||||
data class TrackerDetailsState(
|
||||
val tracker: Tracker? = null,
|
||||
val isBlockAllActivated: Boolean = false,
|
||||
val detectedCount: Int = 0,
|
||||
val blockedCount: Int = 0,
|
||||
val leakedCount: Int = 0,
|
||||
val appList: List<ToggleableApp> = emptyList(),
|
||||
val isTrackersBlockingEnabled: Boolean = false
|
||||
)
|
|
@ -0,0 +1,134 @@
|
|||
/*
|
||||
* Copyright (C) 2024 E FOUNDATION
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.features.trackers.trackerdetails
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import foundation.e.advancedprivacy.domain.entities.DisplayableApp
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackerDetailsUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.features.trackers.URL_LEARN_MORE_ABOUT_TRACKERS
|
||||
import foundation.e.advancedprivacy.trackers.domain.entities.Tracker
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class TrackerDetailsViewModel(
|
||||
private val tracker: Tracker,
|
||||
private val trackersStateUseCase: TrackersStateUseCase,
|
||||
private val trackersStatisticsUseCase: TrackersStatisticsUseCase,
|
||||
private val trackerDetailsUseCase: TrackerDetailsUseCase,
|
||||
private val getQuickPrivacyStateUseCase: GetQuickPrivacyStateUseCase
|
||||
) : ViewModel() {
|
||||
private val _state = MutableStateFlow(TrackerDetailsState(tracker = tracker))
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private val _singleEvents = MutableSharedFlow<SingleEvent>()
|
||||
val singleEvents = _singleEvents.asSharedFlow()
|
||||
|
||||
suspend fun doOnStartedState() = withContext(Dispatchers.IO) {
|
||||
merge(
|
||||
getQuickPrivacyStateUseCase.trackerMode.map {
|
||||
_state.update { s -> s.copy(isTrackersBlockingEnabled = it != FeatureMode.VULNERABLE) }
|
||||
},
|
||||
trackersStatisticsUseCase.listenUpdates().map { fetchStatistics() }
|
||||
).collect { }
|
||||
}
|
||||
|
||||
fun onToggleUnblockApp(app: DisplayableApp, isBlocked: Boolean) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
if (!state.value.isTrackersBlockingEnabled) {
|
||||
_singleEvents.emit(SingleEvent.ToastTrackersControlDisabled)
|
||||
}
|
||||
|
||||
trackersStateUseCase.blockTracker(app, tracker, isBlocked)
|
||||
updateWhitelist()
|
||||
}
|
||||
}
|
||||
|
||||
fun onToggleBlockAll(isBlocked: Boolean) {
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
if (!state.value.isTrackersBlockingEnabled) {
|
||||
_singleEvents.emit(SingleEvent.ToastTrackersControlDisabled)
|
||||
}
|
||||
trackerDetailsUseCase.toggleTrackerWhitelist(
|
||||
tracker,
|
||||
state.value.appList.map { it.app },
|
||||
isBlocked
|
||||
)
|
||||
_state.update {
|
||||
it.copy(
|
||||
isBlockAllActivated = !trackersStateUseCase.isWhitelisted(tracker)
|
||||
)
|
||||
}
|
||||
updateWhitelist()
|
||||
}
|
||||
}
|
||||
|
||||
fun onClickLearnMore() {
|
||||
viewModelScope.launch {
|
||||
_singleEvents.emit(SingleEvent.OpenUrl(Uri.parse(URL_LEARN_MORE_ABOUT_TRACKERS)))
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun fetchStatistics() = withContext(Dispatchers.IO) {
|
||||
val (blocked, leaked) = trackerDetailsUseCase.getCalls(tracker)
|
||||
val appsWhitWhiteListState = trackerDetailsUseCase.getAppsWithBlockedState(tracker)
|
||||
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
isBlockAllActivated = !trackersStateUseCase.isWhitelisted(tracker),
|
||||
detectedCount = appsWhitWhiteListState.size,
|
||||
blockedCount = blocked,
|
||||
leakedCount = leaked,
|
||||
appList = appsWhitWhiteListState
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun updateWhitelist() {
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
isBlockAllActivated = !trackersStateUseCase.isWhitelisted(tracker),
|
||||
appList = trackerDetailsUseCase.enrichWithBlockedState(
|
||||
s.appList.map { it.app },
|
||||
tracker
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
sealed class SingleEvent {
|
||||
data class ErrorEvent(@StringRes val errorResId: Int) : SingleEvent()
|
||||
object ToastTrackersControlDisabled : SingleEvent()
|
||||
data class OpenUrl(val url: Uri) : SingleEvent()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
/*
|
||||
* Copyright (C) 2023 MURENA SAS
|
||||
* Copyright (C) 2021 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.main
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.navigation.NavDeepLinkBuilder
|
||||
import androidx.navigation.findNavController
|
||||
import foundation.e.advancedprivacy.R
|
||||
|
||||
class MainActivity : FragmentActivity(R.layout.activity_main) {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
findNavController(R.id.nav_host_fragment).handleDeepLink(intent)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun deepLinkBuilder(context: Context) = NavDeepLinkBuilder(context)
|
||||
.setGraph(R.navigation.nav_graph)
|
||||
.setComponentName(MainActivity::class.java)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy
|
||||
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import foundation.e.advancedprivacy.domain.usecases.TrackersStatisticsUseCase
|
||||
import foundation.e.advancedprivacy.widget.State
|
||||
import foundation.e.advancedprivacy.widget.render
|
||||
import foundation.e.advancedprivacy.widget.renderAll
|
||||
import java.time.temporal.ChronoUnit
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.FlowPreview
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.debounce
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.sample
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Implementation of App Widget functionality.
|
||||
*/
|
||||
class Widget : AppWidgetProvider() {
|
||||
|
||||
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
|
||||
appWidgetIds.forEach { id ->
|
||||
render(context, state.value, appWidgetManager, id)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onEnabled(context: Context) {
|
||||
// Enter relevant functionality for when the first widget is created
|
||||
}
|
||||
|
||||
override fun onDisabled(context: Context) {
|
||||
// Enter relevant functionality for when the last widget is disabled
|
||||
}
|
||||
|
||||
companion object {
|
||||
private var updateWidgetJob: Job? = null
|
||||
|
||||
private var state: StateFlow<State> = MutableStateFlow(State())
|
||||
|
||||
private const val DARK_TEXT_KEY = "foundation.e.blisslauncher.WIDGET_OPTION_DARK_TEXT"
|
||||
var isDarkText = false
|
||||
|
||||
@OptIn(FlowPreview::class)
|
||||
private fun initState(
|
||||
getPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
|
||||
trackersStatisticsUseCase: TrackersStatisticsUseCase,
|
||||
coroutineScope: CoroutineScope
|
||||
): StateFlow<State> {
|
||||
return combine(
|
||||
getPrivacyStateUseCase.trackerMode,
|
||||
getPrivacyStateUseCase.locationMode,
|
||||
getPrivacyStateUseCase.ipScramblingMode
|
||||
) { trackerMode, locationMode, ipScramblingMode ->
|
||||
State(
|
||||
trackerMode = trackerMode,
|
||||
locationMode = locationMode,
|
||||
ipScramblingMode = ipScramblingMode
|
||||
)
|
||||
}.sample(50)
|
||||
.combine(
|
||||
merge(
|
||||
trackersStatisticsUseCase.listenUpdates()
|
||||
.onStart { emit(Unit) }
|
||||
.debounce(5000),
|
||||
flow {
|
||||
while (true) {
|
||||
emit(Unit)
|
||||
delay(ChronoUnit.HOURS.duration.toMillis())
|
||||
}
|
||||
}
|
||||
|
||||
)
|
||||
) { state, _ ->
|
||||
state.copy(
|
||||
blockedCallsCount = trackersStatisticsUseCase.getLastMonthBlockedLeaksCount(),
|
||||
appsWithCallsCount = trackersStatisticsUseCase.getLastMonthAppsWithBlockedLeaksCount()
|
||||
)
|
||||
}.stateIn(
|
||||
scope = coroutineScope,
|
||||
started = SharingStarted.Eagerly,
|
||||
initialValue = State()
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(DelicateCoroutinesApi::class)
|
||||
fun startListening(
|
||||
appContext: Context,
|
||||
getPrivacyStateUseCase: GetQuickPrivacyStateUseCase,
|
||||
trackersStatisticsUseCase: TrackersStatisticsUseCase
|
||||
) {
|
||||
state = initState(
|
||||
getPrivacyStateUseCase,
|
||||
trackersStatisticsUseCase,
|
||||
GlobalScope
|
||||
)
|
||||
|
||||
updateWidgetJob?.cancel()
|
||||
updateWidgetJob = GlobalScope.launch(Dispatchers.Main) {
|
||||
state.collect {
|
||||
renderAll(appContext, it)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onAppWidgetOptionsChanged(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, newOptions: Bundle?) {
|
||||
super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions)
|
||||
if (newOptions != null) {
|
||||
isDarkText = newOptions.getBoolean(DARK_TEXT_KEY)
|
||||
}
|
||||
|
||||
render(context, state.value, appWidgetManager, appWidgetId)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
/*
|
||||
* Copyright (C) 2022 - 2024 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.widget
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import foundation.e.advancedprivacy.core.utils.goAsync
|
||||
import foundation.e.advancedprivacy.domain.usecases.GetQuickPrivacyStateUseCase
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import org.koin.java.KoinJavaComponent.get
|
||||
|
||||
class WidgetCommandReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
val backgroundScope = get<CoroutineScope>(CoroutineScope::class.java)
|
||||
val getQuickPrivacyStateUseCase = get<GetQuickPrivacyStateUseCase>(GetQuickPrivacyStateUseCase::class.java)
|
||||
|
||||
goAsync(backgroundScope) {
|
||||
val featureEnabled = intent?.extras?.let { bundle ->
|
||||
if (bundle.containsKey(PARAM_FEATURE_ENABLED)) {
|
||||
bundle.getBoolean(PARAM_FEATURE_ENABLED)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
when (intent?.action) {
|
||||
ACTION_TOGGLE_TRACKERS -> getQuickPrivacyStateUseCase.toggleTrackers(featureEnabled)
|
||||
ACTION_TOGGLE_LOCATION -> getQuickPrivacyStateUseCase.toggleLocation(featureEnabled)
|
||||
ACTION_TOGGLE_IPSCRAMBLING -> getQuickPrivacyStateUseCase.toggleIpScrambling(featureEnabled)
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val ACTION_TOGGLE_TRACKERS = "toggle_trackers"
|
||||
const val ACTION_TOGGLE_LOCATION = "toggle_location"
|
||||
const val ACTION_TOGGLE_IPSCRAMBLING = "toggle_ipscrambling"
|
||||
const val PARAM_FEATURE_ENABLED = "param_feature_enabled"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,273 @@
|
|||
/*
|
||||
* Copyright (C) 2023-2024 MURENA SAS
|
||||
* Copyright (C) 2022 E FOUNDATION
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package foundation.e.advancedprivacy.widget
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.drawable.Icon
|
||||
import android.text.Spannable
|
||||
import android.text.SpannableString
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.view.View.GONE
|
||||
import android.view.View.VISIBLE
|
||||
import android.widget.RemoteViews
|
||||
import androidx.annotation.StringRes
|
||||
import foundation.e.advancedprivacy.R
|
||||
import foundation.e.advancedprivacy.Widget
|
||||
import foundation.e.advancedprivacy.Widget.Companion.isDarkText
|
||||
import foundation.e.advancedprivacy.common.BigNumberFormatter
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureMode
|
||||
import foundation.e.advancedprivacy.domain.entities.FeatureState
|
||||
import foundation.e.advancedprivacy.main.MainActivity
|
||||
import foundation.e.advancedprivacy.widget.WidgetCommandReceiver.Companion.ACTION_TOGGLE_IPSCRAMBLING
|
||||
import foundation.e.advancedprivacy.widget.WidgetCommandReceiver.Companion.ACTION_TOGGLE_LOCATION
|
||||
import foundation.e.advancedprivacy.widget.WidgetCommandReceiver.Companion.ACTION_TOGGLE_TRACKERS
|
||||
import foundation.e.advancedprivacy.widget.WidgetCommandReceiver.Companion.PARAM_FEATURE_ENABLED
|
||||
|
||||
data class State(
|
||||
val trackerMode: FeatureMode = FeatureMode.VULNERABLE,
|
||||
val locationMode: FeatureMode = FeatureMode.VULNERABLE,
|
||||
val ipScramblingMode: FeatureState = FeatureState.STOPPING,
|
||||
val blockedCallsCount: Int = 0,
|
||||
val appsWithCallsCount: Int = 0
|
||||
)
|
||||
|
||||
fun renderAll(context: Context, state: State) {
|
||||
val appWidgetManager = AppWidgetManager.getInstance(context)
|
||||
appWidgetManager.getAppWidgetIds(
|
||||
ComponentName(context, Widget::class.java)
|
||||
).forEach { id ->
|
||||
render(context, state, appWidgetManager, id)
|
||||
}
|
||||
}
|
||||
|
||||
fun render(context: Context, state: State, appWidgetManager: AppWidgetManager, widgetId: Int) {
|
||||
val numberFormatter = BigNumberFormatter(context)
|
||||
|
||||
val views = buildLayout(context, appWidgetManager, widgetId)
|
||||
|
||||
applyDarkText(context, isDarkText, views)
|
||||
|
||||
views.apply {
|
||||
val openPIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
REQUEST_CODE_DASHBOARD,
|
||||
Intent(context, MainActivity::class.java),
|
||||
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
|
||||
)
|
||||
setOnClickPendingIntent(R.id.settings_btn, openPIntent)
|
||||
setOnClickPendingIntent(R.id.widget_container, openPIntent)
|
||||
|
||||
val leaksLabel = context.getString(R.string.widget_data_blocked_trackers_secondary)
|
||||
val countStr = numberFormatter.format(state.blockedCallsCount).toString()
|
||||
if (shouldSplitLeaksCountInTwoLines(countStr, leaksLabel)) {
|
||||
setTextViewText(R.id.data_blocked_trackers_number, countStr)
|
||||
setTextViewText(R.id.data_blocked_trackers_secondary, leaksLabel)
|
||||
setViewVisibility(R.id.data_blocked_trackers_number, VISIBLE)
|
||||
} else {
|
||||
setViewVisibility(R.id.data_blocked_trackers_number, GONE)
|
||||
setTextViewText(
|
||||
R.id.data_blocked_trackers_secondary,
|
||||
buildDataSecondarySpan(context, isDarkText, countStr, R.string.widget_data_blocked_trackers_secondary)
|
||||
)
|
||||
}
|
||||
|
||||
setTextViewText(
|
||||
R.id.data_apps_secondary,
|
||||
buildDataSecondarySpan(
|
||||
context,
|
||||
isDarkText,
|
||||
state.appsWithCallsCount.toString(),
|
||||
R.string.widget_data_apps_secondary
|
||||
)
|
||||
)
|
||||
|
||||
val trackersEnabled = state.trackerMode != FeatureMode.VULNERABLE
|
||||
|
||||
setSwitchState(views, R.id.toggle_trackers, trackersEnabled)
|
||||
|
||||
setOnClickPendingIntent(
|
||||
R.id.trackers_control,
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
REQUEST_CODE_TOGGLE_TRACKERS,
|
||||
Intent(context, WidgetCommandReceiver::class.java).apply {
|
||||
action = ACTION_TOGGLE_TRACKERS
|
||||
putExtra(PARAM_FEATURE_ENABLED, !trackersEnabled)
|
||||
},
|
||||
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
|
||||
)
|
||||
)
|
||||
|
||||
val locationEnabled = state.locationMode != FeatureMode.VULNERABLE
|
||||
setSwitchState(views, R.id.toggle_location, locationEnabled)
|
||||
|
||||
setOnClickPendingIntent(
|
||||
R.id.fake_location,
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
REQUEST_CODE_TOGGLE_LOCATION,
|
||||
Intent(context, WidgetCommandReceiver::class.java).apply {
|
||||
action = ACTION_TOGGLE_LOCATION
|
||||
putExtra(PARAM_FEATURE_ENABLED, !locationEnabled)
|
||||
},
|
||||
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
|
||||
)
|
||||
)
|
||||
|
||||
setSwitchState(views, R.id.toggle_ipscrambling, state.ipScramblingMode.isChecked)
|
||||
|
||||
setOnClickPendingIntent(
|
||||
R.id.ipscrambling,
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
REQUEST_CODE_TOGGLE_IPSCRAMBLING,
|
||||
Intent(context, WidgetCommandReceiver::class.java).apply {
|
||||
action = ACTION_TOGGLE_IPSCRAMBLING
|
||||
putExtra(PARAM_FEATURE_ENABLED, !state.ipScramblingMode.isChecked)
|
||||
},
|
||||
FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
appWidgetManager.updateAppWidget(widgetId, views)
|
||||
}
|
||||
|
||||
private const val REQUEST_CODE_DASHBOARD = 1
|
||||
private const val REQUEST_CODE_TOGGLE_TRACKERS = 4
|
||||
private const val REQUEST_CODE_TOGGLE_LOCATION = 5
|
||||
private const val REQUEST_CODE_TOGGLE_IPSCRAMBLING = 6
|
||||
|
||||
private const val NARROW_MAXWIDTH_DP_BREAKPOINT = 240
|
||||
|
||||
private const val DATA_BLOCKED_TWO_LINES_THRESHOLD_DIGITS = 3
|
||||
private const val DATA_BLOCKED_TWO_LINES_THRESHOLD_LABEL = 14
|
||||
|
||||
private fun buildLayout(context: Context, appWidgetManager: AppWidgetManager, widgetId: Int): RemoteViews {
|
||||
val width = appWidgetManager.getAppWidgetOptions(widgetId)
|
||||
.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
|
||||
|
||||
return RemoteViews(
|
||||
context.packageName,
|
||||
when (width) {
|
||||
in 1..NARROW_MAXWIDTH_DP_BREAKPOINT ->
|
||||
R.layout.widget_narrow
|
||||
else -> R.layout.widget_large
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyDarkText(context: Context, isDarkText: Boolean, views: RemoteViews) {
|
||||
views.apply {
|
||||
// FFFFFF %87
|
||||
val primaryColor = context.getColor(
|
||||
if (isDarkText) {
|
||||
R.color.on_surface_medium_emphasis_light
|
||||
} else {
|
||||
R.color.on_surface_high_emphasis
|
||||
}
|
||||
)
|
||||
|
||||
listOf(
|
||||
R.id.widget_title,
|
||||
R.id.data_blocked_trackers_primary,
|
||||
R.id.data_blocked_trackers_number,
|
||||
R.id.data_apps_primary,
|
||||
R.id.trackers_control_label,
|
||||
R.id.fake_location_label,
|
||||
R.id.ipscrambling_label
|
||||
).forEach {
|
||||
setTextColor(it, primaryColor)
|
||||
}
|
||||
|
||||
listOf(
|
||||
R.id.settings_btn to R.drawable.ic_settings,
|
||||
R.id.data_blocked_trackers_icon to R.drawable.ic_block_24,
|
||||
R.id.data_apps_icon to R.drawable.ic_apps_24
|
||||
).forEach { (viewId, drawableId) ->
|
||||
setImageViewIcon(
|
||||
viewId,
|
||||
Icon.createWithResource(context, drawableId).apply { setTint(primaryColor) }
|
||||
)
|
||||
}
|
||||
|
||||
// FFFFFF %60
|
||||
val secondaryColor = context.getColor(if (isDarkText) R.color.on_surface_disabled_light else R.color.on_primary_medium_emphasis)
|
||||
|
||||
listOf(
|
||||
R.id.period_label,
|
||||
R.id.data_blocked_trackers_secondary
|
||||
).forEach { id ->
|
||||
setTextColor(id, secondaryColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shouldSplitLeaksCountInTwoLines(countStr: String, leaksLabel: String): Boolean {
|
||||
return countStr.length > DATA_BLOCKED_TWO_LINES_THRESHOLD_DIGITS &&
|
||||
(countStr.length + leaksLabel.length) > DATA_BLOCKED_TWO_LINES_THRESHOLD_LABEL
|
||||
}
|
||||
|
||||
private fun buildDataSecondarySpan(context: Context, isDarkText: Boolean, countStr: String, @StringRes secondaryRes: Int): CharSequence {
|
||||
val primaryColor = context.getColor(
|
||||
if (isDarkText) {
|
||||
R.color.on_surface_medium_emphasis_light
|
||||
} else {
|
||||
R.color.on_surface_high_emphasis
|
||||
}
|
||||
)
|
||||
|
||||
val secondaryColor = context.getColor(if (isDarkText) R.color.on_surface_disabled_light else R.color.on_primary_medium_emphasis)
|
||||
|
||||
val secondary = context.getString(secondaryRes)
|
||||
|
||||
val spannable = SpannableString("$countStr $secondary")
|
||||
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(primaryColor),
|
||||
0,
|
||||
countStr.length,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
|
||||
spannable.setSpan(
|
||||
ForegroundColorSpan(secondaryColor),
|
||||
countStr.length,
|
||||
spannable.length,
|
||||
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
|
||||
)
|
||||
return spannable
|
||||
}
|
||||
|
||||
private fun setSwitchState(views: RemoteViews, switchId: Int, checked: Boolean) {
|
||||
views.setImageViewResource(
|
||||
switchId,
|
||||
if (checked) {
|
||||
R.drawable.ic_switch_enabled_raster
|
||||
} else {
|
||||
R.drawable.ic_switch_disabled_raster
|
||||
}
|
||||
)
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:color="@color/accent" android:state_enabled="true" android:state_selected="true"/>
|
||||
<item android:color="@color/accent" android:state_enabled="true" android:state_checked="true"/>
|
||||
<item android:color="@color/background" />
|
||||
</selector>
|
|
@ -0,0 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
<selector xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:color="@color/white" android:state_enabled="true" android:state_selected="true"/>
|
||||
<item android:color="@color/white" android:state_enabled="true" android:state_checked="true"/>
|
||||
<item android:color="@color/accent" />
|
||||
</selector>
|
|
@ -0,0 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
~ Copyright (C) 2021 E FOUNDATION
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
|
||||
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<stroke android:width="1dp" android:color="@color/divider" />
|
||||
<corners android:radius="4dp" />
|
||||
</shape>
|
|
@ -0,0 +1,23 @@
|
|||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
~ Copyright (C) 2021 E FOUNDATION
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
|
||||
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<solid android:color="@color/dark_color" />
|
||||
<corners android:radius="19dp" />
|
||||
</shape>
|
|
@ -0,0 +1,21 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<stroke android:width="1dp" android:color="@color/divider" />
|
||||
<corners android:radius="12dp" />
|
||||
</shape>
|
|
@ -0,0 +1,21 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<stroke android:width="1dp" android:color="@color/on_primary_disabled" />
|
||||
<corners android:radius="8dp" />
|
||||
</shape>
|
|
@ -0,0 +1,22 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="@color/white" />
|
||||
<corners android:radius="12dp" />
|
||||
</shape>
|
|
@ -0,0 +1,28 @@
|
|||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
~ Copyright (C) 2022 E FOUNDATION
|
||||
~
|
||||
~ 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/>.
|
||||
-->
|
||||
|
||||
<!--
|
||||
Background for widgets to make the rounded corners based on the
|
||||
appWidgetRadius attribute value
|
||||
-->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle"
|
||||
>
|
||||
|
||||
<corners android:radius="12dp" />
|
||||
<solid android:color="@color/widget_background" />
|
||||
</shape>
|
|
@ -0,0 +1,26 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ This program is free software: you can redistribute it and/or modify
|
||||
~ it under the terms of the GNU General Public License as published by
|
||||
~ the Free Software Foundation, either version 3 of the License, or
|
||||
~ (at your option) any later version.
|
||||
~
|
||||
~ This program is distributed in the hope that it will be useful,
|
||||
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
~ GNU General Public License for more details.
|
||||
~
|
||||
~ You should have received a copy of the GNU General Public License
|
||||
~ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M4,8H8V4H4V8ZM10,20H14V16H10V20ZM4,20H8V16H4V20ZM4,14H8V10H4V14ZM10,14H14V10H10V14ZM16,4V8H20V4H16ZM10,8H14V4H10V8ZM16,14H20V10H16V14ZM16,20H20V16H16V20Z"
|
||||
android:fillColor="#000000"/>
|
||||
</vector>
|
|
@ -0,0 +1,18 @@
|
|||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="180dp"
|
||||
android:height="180dp"
|
||||
android:viewportWidth="180"
|
||||
android:viewportHeight="180">
|
||||
<path
|
||||
android:pathData="M37.43,26.81L77.27,26.81A10.61,10.61 0,0 1,87.88 37.43L87.88,77.26A10.61,10.61 0,0 1,77.27 87.88L37.43,87.88A10.61,10.61 0,0 1,26.82 77.26L26.82,37.43A10.61,10.61 0,0 1,37.43 26.81z"
|
||||
android:fillColor="#A1B4BE"/>
|
||||
<path
|
||||
android:pathData="M37.43,92.12L77.27,92.12A10.61,10.61 0,0 1,87.88 102.74L87.88,142.57A10.61,10.61 0,0 1,77.27 153.19L37.43,153.19A10.61,10.61 0,0 1,26.82 142.57L26.82,102.74A10.61,10.61 0,0 1,37.43 92.12z"
|
||||
android:fillColor="#A1B4BE"/>
|
||||
<path
|
||||
android:pathData="M102.74,26.81L142.57,26.81A10.61,10.61 0,0 1,153.19 37.43L153.19,77.26A10.61,10.61 0,0 1,142.57 87.88L102.74,87.88A10.61,10.61 0,0 1,92.12 77.26L92.12,37.43A10.61,10.61 0,0 1,102.74 26.81z"
|
||||
android:fillColor="#A1B4BE"/>
|
||||
<path
|
||||
android:pathData="M147.81,128.51C144.61,122.96 146.53,115.85 152.11,112.62L146.11,102.23C144.4,103.23 142.4,103.81 140.27,103.81C133.86,103.81 128.66,98.58 128.66,92.12H116.66C116.68,94.12 116.18,96.13 115.11,97.98C111.91,103.53 104.79,105.42 99.2,102.2L93.2,112.59C94.93,113.57 96.42,115.01 97.49,116.86C100.68,122.4 98.77,129.49 93.21,132.73L99.21,143.13C100.92,142.13 102.9,141.56 105.02,141.56C111.41,141.56 116.59,146.76 116.63,153.19H128.63C128.63,151.21 129.12,149.22 130.18,147.39C133.38,141.85 140.49,139.96 146.07,143.15L152.07,132.76C150.35,131.78 148.87,130.35 147.81,128.51ZM122.66,135.02C115.83,135.02 110.29,129.49 110.29,122.65C110.29,115.82 115.83,110.29 122.66,110.29C129.49,110.29 135.02,115.82 135.02,122.65C135.02,129.49 129.49,135.02 122.66,135.02Z"
|
||||
android:fillColor="#A1B4BE"/>
|
||||
</vector>
|
|
@ -0,0 +1,26 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (C) 2023 MURENA SAS
|
||||
~
|
||||
~ This program is free software: you can redistribute it and/or modify
|
||||
~ it under the terms of the GNU General Public License as published by
|
||||
~ the Free Software Foundation, either version 3 of the License, or
|
||||
~ (at your option) any later version.
|
||||
~
|
||||
~ This program is distributed in the hope that it will be useful,
|
||||
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
~ GNU General Public License for more details.
|
||||
~
|
||||
~ You should have received a copy of the GNU General Public License
|
||||
~ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2ZM4,12C4,7.58 7.58,4 12,4C13.85,4 15.55,4.63 16.9,5.69L5.69,16.9C4.63,15.55 4,13.85 4,12ZM12,20C10.15,20 8.45,19.37 7.1,18.31L18.31,7.1C19.37,8.45 20,10.15 20,12C20,16.42 16.42,20 12,20Z"
|
||||
android:fillColor="#000000"/>
|
||||
</vector>
|
|
@ -0,0 +1,27 @@
|
|||
<!--
|
||||
Copyright (C) 2017 The Android Open Source Project
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
-->
|
||||
|
||||
<vector
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:autoMirrored="true"
|
||||
android:height="24dp"
|
||||
android:width="24dp"
|
||||
android:viewportHeight="24.0"
|
||||
android:viewportWidth="24.0"
|
||||
android:tint="@color/iconInvertedColor">
|
||||
<path android:fillColor="#FF000000"
|
||||
android:pathData="M9.71,18.71l-1.42,-1.42l5.3,-5.29l-5.3,-5.29l1.42,-1.42l6.7,6.71z"/>
|
||||
</vector>
|
|
@ -0,0 +1,9 @@
|
|||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="16dp"
|
||||
android:height="16dp"
|
||||
android:viewportWidth="16"
|
||||
android:viewportHeight="16">
|
||||
<path
|
||||
android:pathData="M12.667,4.273L11.727,3.333L8,7.06L4.273,3.333L3.333,4.273L7.06,8L3.333,11.727L4.273,12.667L8,8.94L11.727,12.667L12.667,11.727L8.94,8L12.667,4.273Z"
|
||||
android:fillColor="#ffffff"/>
|
||||
</vector>
|
|
@ -0,0 +1,5 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_e_app_logo"/>
|
||||
</adaptive-icon>
|
|
@ -0,0 +1,15 @@
|
|||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:pathData="M12,2C7.8,2 4,5.22 4,10.2C4,13.52 6.67,17.45 12,22C17.33,17.45 20,13.52 20,10.2C20,5.22 16.2,2 12,2ZM12,19.33C7.95,15.63 6,12.54 6,10.19C6,6.57 8.65,4 12,4C15.35,4 18,6.57 18,10.2C18,12.54 16.05,15.64 12,19.33Z"
|
||||
android:fillColor="#000000"/>
|
||||
<path
|
||||
android:pathData="M13,6H11V11H13V6Z"
|
||||
android:fillColor="#000000"/>
|
||||
<path
|
||||
android:pathData="M13,13H11V15H13V13Z"
|
||||
android:fillColor="#000000"/>
|
||||
</vector>
|
|
@ -0,0 +1,20 @@
|
|||
<!--
|
||||
~ Copyright (C) 2022 E FOUNDATION
|
||||
~
|
||||
~ This program is free software: you can redistribute it and/or modify
|
||||
~ it under the terms of the GNU General Public License as published by
|
||||
~ the Free Software Foundation, either version 3 of the License, or
|
||||
~ (at your option) any later version.
|
||||
~
|
||||
~ This program is distributed in the hope that it will be useful,
|
||||
~ but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
~ GNU General Public License for more details.
|
||||
~
|
||||
~ You should have received a copy of the GNU General Public License
|
||||
~ along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
-->
|
||||
<vector android:height="16dp" android:viewportHeight="24"
|
||||
android:viewportWidth="24" android:width="16dp" xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<path android:fillColor="#000000" android:pathData="M11,7H13V9H11V7ZM11,11H13V17H11V11ZM12,2C6.48,2 2,6.48 2,12C2,17.52 6.48,22 12,22C17.52,22 22,17.52 22,12C22,6.48 17.52,2 12,2ZM12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20Z"/>
|
||||
</vector>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue