v0.6.5
This commit is contained in:
16
.editorconfig
Normal file
16
.editorconfig
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
root = true
|
||||||
|
|
||||||
|
[*]
|
||||||
|
charset = utf-8
|
||||||
|
insert_final_newline = true
|
||||||
|
trim_trailing_whitespace = true
|
||||||
|
|
||||||
|
[*.{kt,kts}]
|
||||||
|
indent_size = 4
|
||||||
|
ij_kotlin_allow_trailing_comma = true
|
||||||
|
ij_kotlin_allow_trailing_comma_on_call_site = true
|
||||||
|
ij_kotlin_name_count_to_use_star_import = 999
|
||||||
|
ij_kotlin_name_count_to_use_star_import_for_members = 999
|
||||||
|
|
||||||
|
[*.{yml,yaml}]
|
||||||
|
indent_size = 2
|
||||||
32
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
32
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
---
|
||||||
|
name: Bug report
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: "[BUG]"
|
||||||
|
labels: bug
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
1. Go to '...'
|
||||||
|
2. Click on '....'
|
||||||
|
3. Scroll down to '....'
|
||||||
|
4. See error
|
||||||
|
|
||||||
|
**Expected behavior**
|
||||||
|
A clear and concise description of what you expected to happen.
|
||||||
|
|
||||||
|
**Screenshots**
|
||||||
|
If applicable, add screenshots to help explain your problem.
|
||||||
|
|
||||||
|
**Smartphone (please complete the following information):**
|
||||||
|
- Device: [e.g. Pixel 6]
|
||||||
|
- OS: [e.g. Android 12L]
|
||||||
|
- Version [e.g. v0.5.1]
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here.
|
||||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
name: Feature request
|
||||||
|
about: Suggest an idea for this project
|
||||||
|
title: ''
|
||||||
|
labels: enhancement
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Is your feature request related to a problem? Please describe.**
|
||||||
|
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||||
|
|
||||||
|
**Describe the solution you'd like**
|
||||||
|
A clear and concise description of what you want to happen.
|
||||||
|
|
||||||
|
**Describe alternatives you've considered**
|
||||||
|
A clear and concise description of any alternative solutions or features you've considered.
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context or screenshots about the feature request here.
|
||||||
26
.github/ISSUE_TEMPLATE/quick-crash-report.md
vendored
Normal file
26
.github/ISSUE_TEMPLATE/quick-crash-report.md
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
---
|
||||||
|
name: Quick crash report
|
||||||
|
about: Create a report to help us improve
|
||||||
|
title: "[Crash]"
|
||||||
|
labels: bug
|
||||||
|
assignees: ''
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Describe the bug**
|
||||||
|
A clear and concise description of what the bug is.
|
||||||
|
|
||||||
|
**To Reproduce**
|
||||||
|
Steps to reproduce the behavior:
|
||||||
|
1. Go to '...'
|
||||||
|
2. Click on '....'
|
||||||
|
3. Scroll down to '....'
|
||||||
|
4. See error
|
||||||
|
|
||||||
|
**Smartphone (please complete the following information):**
|
||||||
|
- Device: [e.g. Pixel 6]
|
||||||
|
- OS: [e.g. Android 12L]
|
||||||
|
- Version [e.g. v0.5.1]
|
||||||
|
|
||||||
|
**Additional context**
|
||||||
|
Add any other context about the problem here. Like what are the changes in settings that you made.
|
||||||
74
.github/workflows/build_debug.yml
vendored
Normal file
74
.github/workflows/build_debug.yml
vendored
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
name: Build Debug APK
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- 'main'
|
||||||
|
paths-ignore:
|
||||||
|
- '**.md'
|
||||||
|
- '**.yml'
|
||||||
|
- '**.xml'
|
||||||
|
pull_request_review:
|
||||||
|
paths-ignore:
|
||||||
|
- '**.md'
|
||||||
|
types: submitted
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: true
|
||||||
|
|
||||||
|
- name: Validate Gradle Wrapper
|
||||||
|
uses: gradle/actions/setup-gradle@v4
|
||||||
|
|
||||||
|
- name: Setup Gradle
|
||||||
|
uses: gradle/wrapper-validation-action@v3
|
||||||
|
|
||||||
|
- name: Set up Java 17
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
java-version: 17
|
||||||
|
distribution: 'adopt'
|
||||||
|
cache: gradle
|
||||||
|
|
||||||
|
- name: Grant execution permission to Gradle Wrapper
|
||||||
|
run: chmod +x gradlew
|
||||||
|
|
||||||
|
- name: Build Debug APK
|
||||||
|
run: ./gradlew assembleDebug
|
||||||
|
|
||||||
|
- name: Sign Apk
|
||||||
|
continue-on-error: true
|
||||||
|
id: sign_apk
|
||||||
|
uses: r0adkll/sign-android-release@v1
|
||||||
|
with:
|
||||||
|
releaseDir: app/build/outputs/apk/debug
|
||||||
|
signingKeyBase64: ${{ secrets.KEY_BASE64 }}
|
||||||
|
alias: ${{ secrets.KEY_ALIAS }}
|
||||||
|
keyStorePassword: ${{ secrets.KEYSTORE_PASS }}
|
||||||
|
keyPassword: ${{ secrets.KEYSTORE_PASS }}
|
||||||
|
|
||||||
|
- name: Remove file that aren't signed
|
||||||
|
continue-on-error: true
|
||||||
|
run: |
|
||||||
|
ls | grep 'signed\.apk$' && find . -type f -name '*.apk' ! -name '*-signed.apk' -delete
|
||||||
|
|
||||||
|
- name: Upload the APK
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: debug
|
||||||
|
path: app/build/outputs/apk/debug/app-debug*.apk
|
||||||
94
.github/workflows/release_build.yml
vendored
Normal file
94
.github/workflows/release_build.yml
vendored
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
name: Build Release APK
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: "release-build"
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: true
|
||||||
|
|
||||||
|
- name: Validate Gradle Wrapper
|
||||||
|
uses: gradle/actions/setup-gradle@v4
|
||||||
|
|
||||||
|
- name: Setup Gradle
|
||||||
|
uses: gradle/wrapper-validation-action@v3
|
||||||
|
|
||||||
|
- name: Set up Java 17
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
java-version: 17
|
||||||
|
distribution: 'adopt'
|
||||||
|
cache: gradle
|
||||||
|
|
||||||
|
- name: Grant execution permission to Gradle Wrapper
|
||||||
|
run: chmod +x gradlew
|
||||||
|
|
||||||
|
- name: Build Release APK
|
||||||
|
run: ./gradlew assembleRelease
|
||||||
|
|
||||||
|
- name: Checks
|
||||||
|
run: find . -type f -name "*.apk"
|
||||||
|
|
||||||
|
- uses: r0adkll/sign-android-release@v1
|
||||||
|
name: Signing APK
|
||||||
|
id: sign_app
|
||||||
|
with:
|
||||||
|
releaseDirectory: app/build/outputs/apk/release
|
||||||
|
signingKeyBase64: ${{ secrets.KEY_BASE64 }}
|
||||||
|
alias: ${{ secrets.KEY_ALIAS }}
|
||||||
|
keyStorePassword: ${{ secrets.KEYSTORE_PASS }}
|
||||||
|
keyPassword: ${{ secrets.KEYSTORE_PASS }}
|
||||||
|
env:
|
||||||
|
BUILD_TOOLS_VERSION: "35.0.0"
|
||||||
|
|
||||||
|
- name: Extract Version Code
|
||||||
|
id: extract_version
|
||||||
|
run: |
|
||||||
|
VERSION_CODE=$(grep -oP '(?<=versionCode=)\d+' app/build.gradle) # Adjust path to your build.gradle
|
||||||
|
echo "::set-output name=version_code::$VERSION_CODE"
|
||||||
|
echo "Version Code: $VERSION_CODE"
|
||||||
|
|
||||||
|
- name: Read Changelog
|
||||||
|
id: read_changelog
|
||||||
|
run: |
|
||||||
|
CHANGELOG_PATH="metadata/en-US/changelogs/${{ steps.extract_version.outputs.version_code }}.txt"
|
||||||
|
if [[ -f "$CHANGELOG_PATH" ]]; then
|
||||||
|
CHANGELOG=$(cat "$CHANGELOG_PATH")
|
||||||
|
echo "::set-output name=changelog::$CHANGELOG"
|
||||||
|
else
|
||||||
|
echo "::set-output name=changelog::No changelog found for this version."
|
||||||
|
echo "No changelog found at: $CHANGELOG_PATH"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- uses: softprops/action-gh-release@v2
|
||||||
|
name: Create Release
|
||||||
|
id: publish_release
|
||||||
|
with:
|
||||||
|
body: ${{ steps.read_changelog.outputs.changelog }}
|
||||||
|
tag_name: ${{ github.ref }}
|
||||||
|
name: Release ${{ github.ref }}
|
||||||
|
files: ${{steps.sign_app.outputs.signedReleaseFile}}
|
||||||
|
draft: true
|
||||||
|
prerelease: false
|
||||||
|
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: Signed APK
|
||||||
|
path: ${{steps.sign_app.outputs.signedReleaseFile}}
|
||||||
22
.gitignore
vendored
Normal file
22
.gitignore
vendored
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
*.iml
|
||||||
|
.gradle
|
||||||
|
/local.properties
|
||||||
|
/.idea/caches
|
||||||
|
/.idea/libraries
|
||||||
|
/.idea/modules.xml
|
||||||
|
/.idea/workspace.xml
|
||||||
|
/.idea/navEditor.xml
|
||||||
|
/.idea/assetWizardSettings.xml
|
||||||
|
.DS_Store
|
||||||
|
/app/build/
|
||||||
|
/build
|
||||||
|
/captures
|
||||||
|
.externalNativeBuild
|
||||||
|
.cxx
|
||||||
|
local.properties
|
||||||
|
/.idea/
|
||||||
|
/build-logic/structure/build/
|
||||||
|
/core-datastore/build/
|
||||||
|
/app/release/
|
||||||
|
/app/alpha/
|
||||||
|
/.kotlin/
|
||||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
75
README.md
75
README.md
@@ -1,3 +1,74 @@
|
|||||||
# Releases
|
<div align="center">
|
||||||
|
|
||||||
This Repository gets updated with only the newest Droid-ify Version. This is so that FeloStore (hopefully) never breaks when syncing code from upstream
|
<img width="" src="metadata/en-US/images/featureGraphic.png" alt="Droid-ify" align="center">
|
||||||
|
|
||||||
|
[](https://github.com/Iamlooker/Droid-ify/stargazers)
|
||||||
|
[](https://github.com/Iamlooker/Droid-ify/blob/master/COPYING)
|
||||||
|
[](https://github.com/Iamlooker/Droid-ify/releases/)
|
||||||
|
[](https://github.com/Iamlooker/Droid-ify/releases/latest)
|
||||||
|
[](https://f-droid.org/packages/com.looker.droidify)
|
||||||
|
</div>
|
||||||
|
<div align="left">
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
* Material & Clean design
|
||||||
|
* Fast repository syncing
|
||||||
|
* Smooth user experience
|
||||||
|
* Feature-rich
|
||||||
|
|
||||||
|
## Screenshots
|
||||||
|
|
||||||
|
<img src="metadata/en-US/images/phoneScreenshots/1.png" width="25%" /><img src="metadata/en-US/images/phoneScreenshots/2.png" width="25%" /><img src="metadata/en-US/images/phoneScreenshots/3.png" width="25%" /><img src="metadata/en-US/images/phoneScreenshots/4.png" width="25%" />
|
||||||
|
|
||||||
|
## Building and Installing
|
||||||
|
|
||||||
|
1. **Install Android Studio**:
|
||||||
|
- Download and install [Android Studio](https://developer.android.com/studio) on your computer
|
||||||
|
if you haven't already.
|
||||||
|
|
||||||
|
2. **Clone the Repository**:
|
||||||
|
- Open Android Studio and select "Project from Version Control."
|
||||||
|
- Paste the link to this repository to clone it to your local machine.
|
||||||
|
|
||||||
|
3. **Build the APK**:
|
||||||
|
- In Android Studio, navigate to `Build > APK`.
|
||||||
|
- Select "Create New Keystore" and enter the required information, including a password.
|
||||||
|
- Wait for the build process to finish.
|
||||||
|
|
||||||
|
## TODO
|
||||||
|
|
||||||
|
- [ ] Add support for `index-v2`
|
||||||
|
- [ ] Add detekt code-analysis
|
||||||
|
- [ ] Add GitHub Repo feature
|
||||||
|
|
||||||
|
## Contribution
|
||||||
|
|
||||||
|
- Pick any issue you would like to resolve
|
||||||
|
- Fork the project
|
||||||
|
- Open a Pull Request
|
||||||
|
- Your PR will undergo review
|
||||||
|
|
||||||
|
## Translations
|
||||||
|
|
||||||
|
[](https://hosted.weblate.org/engage/droidify/?utm_source=widget)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
```
|
||||||
|
Droid-ify
|
||||||
|
|
||||||
|
Copyright (C) 2023 LooKeR
|
||||||
|
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/>.
|
||||||
|
```
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|||||||
15
STATUS.md
Normal file
15
STATUS.md
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
_17-Aug-2023_
|
||||||
|
# Project Status
|
||||||
|
|
||||||
|
I was holding back releases, because I was re-writing the whole structure of the app. But I think this is taking too long.
|
||||||
|
It is only natural that users will grow impatient for an update, thats why I will be releasing new versions soon.
|
||||||
|
|
||||||
|
## Why the delay:
|
||||||
|
- I had exams and submissions in my college
|
||||||
|
- I am really unwell mentally
|
||||||
|
- I was not able to create a solid structure for the new backend
|
||||||
|
|
||||||
|
## What now?
|
||||||
|
- Next release will be on **19-Aug**, and will contain many bug fixes and stability improvements.
|
||||||
|
- All the [progress](https://github.com/Droid-ify/client/pull/309) made in past months is still here and will help in future.
|
||||||
|
- We will be missing on the new index format introduced by fdroid for some future releases.
|
||||||
195
app/build.gradle.kts
Normal file
195
app/build.gradle.kts
Normal file
@@ -0,0 +1,195 @@
|
|||||||
|
import com.android.build.gradle.internal.tasks.factory.dependsOn
|
||||||
|
import org.jlleitschuh.gradle.ktlint.reporter.ReporterType
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.android.application)
|
||||||
|
alias(libs.plugins.kotlin.android)
|
||||||
|
alias(libs.plugins.ktlint)
|
||||||
|
alias(libs.plugins.ksp)
|
||||||
|
alias(libs.plugins.hilt)
|
||||||
|
alias(libs.plugins.kotlin.serialization)
|
||||||
|
alias(libs.plugins.kotlin.parcelize)
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
val latestVersionName = "0.6.5"
|
||||||
|
namespace = "com.looker.droidify"
|
||||||
|
buildToolsVersion = "35.0.0"
|
||||||
|
compileSdk = 35
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 23
|
||||||
|
targetSdk = 35
|
||||||
|
applicationId = "com.looker.droidify"
|
||||||
|
versionCode = 650
|
||||||
|
versionName = latestVersionName
|
||||||
|
vectorDrawables.useSupportLibrary = false
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
isCoreLibraryDesugaringEnabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "17"
|
||||||
|
freeCompilerArgs = listOf(
|
||||||
|
"-opt-in=kotlin.RequiresOptIn",
|
||||||
|
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
|
||||||
|
"-opt-in=kotlinx.coroutines.FlowPreview",
|
||||||
|
"-Xcontext-receivers"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
androidResources {
|
||||||
|
generateLocaleConfig = true
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSets.forEach { source ->
|
||||||
|
val javaDir = source.java.srcDirs.find { it.name == "java" }
|
||||||
|
source.java {
|
||||||
|
srcDir(File(javaDir?.parentFile, "kotlin"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
debug {
|
||||||
|
applicationIdSuffix = ".debug"
|
||||||
|
resValue("string", "application_name", "Droid-ify-Debug")
|
||||||
|
}
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = true
|
||||||
|
isShrinkResources = true
|
||||||
|
resValue("string", "application_name", "Droid-ify")
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard.pro"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
create("alpha") {
|
||||||
|
initWith(getByName("debug"))
|
||||||
|
applicationIdSuffix = ".alpha"
|
||||||
|
resValue("string", "application_name", "Droid-ify Alpha")
|
||||||
|
proguardFiles(
|
||||||
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
|
"proguard.pro"
|
||||||
|
)
|
||||||
|
isDebuggable = true
|
||||||
|
isMinifyEnabled = true
|
||||||
|
}
|
||||||
|
all {
|
||||||
|
buildConfigField(
|
||||||
|
type = "String",
|
||||||
|
name = "VERSION_NAME",
|
||||||
|
value = "\"v$latestVersionName\""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
packaging {
|
||||||
|
resources {
|
||||||
|
excludes += listOf(
|
||||||
|
"/DebugProbesKt.bin",
|
||||||
|
"/kotlin/**.kotlin_builtins",
|
||||||
|
"/kotlin/**.kotlin_metadata",
|
||||||
|
"/META-INF/**.kotlin_module",
|
||||||
|
"/META-INF/**.pro",
|
||||||
|
"/META-INF/**.version",
|
||||||
|
"/META-INF/{AL2.0,LGPL2.1,LICENSE*}",
|
||||||
|
"/META-INF/versions/9/previous-**.bin",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buildFeatures {
|
||||||
|
resValues = true
|
||||||
|
viewBinding = true
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
|
dependenciesInfo {
|
||||||
|
includeInApk = false
|
||||||
|
includeInBundle = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ktlint {
|
||||||
|
android.set(true)
|
||||||
|
ignoreFailures.set(true)
|
||||||
|
debug.set(true)
|
||||||
|
reporters {
|
||||||
|
reporter(ReporterType.HTML)
|
||||||
|
}
|
||||||
|
filter {
|
||||||
|
exclude("**/generated/**")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
coreLibraryDesugaring(libs.desugaring)
|
||||||
|
|
||||||
|
implementation(libs.material)
|
||||||
|
implementation(libs.core.ktx)
|
||||||
|
implementation(libs.activity)
|
||||||
|
implementation(libs.appcompat)
|
||||||
|
implementation(libs.fragment.ktx)
|
||||||
|
implementation(libs.lifecycle.viewModel)
|
||||||
|
implementation(libs.recyclerview)
|
||||||
|
implementation(libs.sqlite.ktx)
|
||||||
|
|
||||||
|
implementation(libs.image.viewer)
|
||||||
|
implementation(libs.bundles.coil)
|
||||||
|
|
||||||
|
implementation(libs.datastore.core)
|
||||||
|
implementation(libs.datastore.proto)
|
||||||
|
|
||||||
|
implementation(libs.kotlin.stdlib)
|
||||||
|
implementation(libs.datetime)
|
||||||
|
|
||||||
|
implementation(libs.coroutines.core)
|
||||||
|
implementation(libs.coroutines.android)
|
||||||
|
implementation(libs.coroutines.guava)
|
||||||
|
|
||||||
|
implementation(libs.libsu.core)
|
||||||
|
implementation(libs.shizuku.api)
|
||||||
|
api(libs.shizuku.provider)
|
||||||
|
|
||||||
|
implementation(libs.jackson.core)
|
||||||
|
implementation(libs.serialization)
|
||||||
|
|
||||||
|
implementation(libs.ktor.core)
|
||||||
|
implementation(libs.ktor.okhttp)
|
||||||
|
|
||||||
|
implementation(libs.work.ktx)
|
||||||
|
|
||||||
|
implementation(libs.hilt.core)
|
||||||
|
implementation(libs.hilt.android)
|
||||||
|
implementation(libs.hilt.ext.work)
|
||||||
|
ksp(libs.hilt.compiler)
|
||||||
|
ksp(libs.hilt.ext.compiler)
|
||||||
|
|
||||||
|
testImplementation(platform(libs.junit.bom))
|
||||||
|
testImplementation(libs.bundles.test.unit)
|
||||||
|
testRuntimeOnly(libs.junit.platform)
|
||||||
|
androidTestImplementation(platform(libs.junit.bom))
|
||||||
|
androidTestImplementation(libs.bundles.test.android)
|
||||||
|
|
||||||
|
// debugImplementation(libs.leakcanary)
|
||||||
|
}
|
||||||
|
|
||||||
|
// using a task as a preBuild dependency instead of a function that takes some time insures that it runs
|
||||||
|
task("detectAndroidLocals") {
|
||||||
|
val langsList: MutableSet<String> = HashSet()
|
||||||
|
|
||||||
|
// in /res are (almost) all languages that have a translated string is saved. this is safer and saves some time
|
||||||
|
fileTree("src/main/res").visit {
|
||||||
|
if (this.file.path.endsWith("strings.xml") &&
|
||||||
|
this.file.canonicalFile.readText().contains("<string")
|
||||||
|
) {
|
||||||
|
var languageCode = this.file.parentFile.name.replace("values-", "")
|
||||||
|
languageCode = if (languageCode == "values") "en" else languageCode
|
||||||
|
langsList.add(languageCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val langsListString = "{${langsList.sorted().joinToString(",") { "\"${it}\"" }}}"
|
||||||
|
android.defaultConfig.buildConfigField("String[]", "DETECTED_LOCALES", langsListString)
|
||||||
|
}
|
||||||
|
tasks.preBuild.dependsOn("detectAndroidLocals")
|
||||||
9
app/proguard.pro
vendored
Normal file
9
app/proguard.pro
vendored
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
-dontobfuscate
|
||||||
|
|
||||||
|
# Disable ServiceLoader reproducibility-breaking optimizations
|
||||||
|
-keep class kotlinx.coroutines.CoroutineExceptionHandler
|
||||||
|
-keep class kotlinx.coroutines.internal.MainDispatcherFactory
|
||||||
|
|
||||||
|
-dontwarn kotlinx.serialization.KSerializer
|
||||||
|
-dontwarn kotlinx.serialization.Serializable
|
||||||
|
-dontwarn org.slf4j.impl.StaticLoggerBinder
|
||||||
BIN
app/src/androidTest/assets/fdroid_index_v1.jar
Normal file
BIN
app/src/androidTest/assets/fdroid_index_v1.jar
Normal file
Binary file not shown.
1
app/src/androidTest/assets/fdroid_index_v1.json
Normal file
1
app/src/androidTest/assets/fdroid_index_v1.json
Normal file
File diff suppressed because one or more lines are too long
1
app/src/androidTest/assets/fdroid_index_v2.json
Normal file
1
app/src/androidTest/assets/fdroid_index_v2.json
Normal file
File diff suppressed because one or more lines are too long
BIN
app/src/androidTest/assets/index-v1.jar
Normal file
BIN
app/src/androidTest/assets/index-v1.jar
Normal file
Binary file not shown.
1
app/src/androidTest/assets/izzy_diff.json
Normal file
1
app/src/androidTest/assets/izzy_diff.json
Normal file
File diff suppressed because one or more lines are too long
BIN
app/src/androidTest/assets/izzy_entry.jar
Normal file
BIN
app/src/androidTest/assets/izzy_entry.jar
Normal file
Binary file not shown.
1
app/src/androidTest/assets/izzy_entry.json
Normal file
1
app/src/androidTest/assets/izzy_entry.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"timestamp": 1725903808000, "version": 20002, "index": {"name": "/index-v2.json", "sha256": "5c5d5b6495efd95c0e7b849df4f1411b6337272cdee2b28defc4eb0f1c4bae42", "size": 7134576, "numPackages": 1201}, "diffs": {"1725491992000": {"name": "/diff/1725491992000.json", "sha256": "58b2633fd72a8b517a69354f15ee88d028c55c92b4122158f0dd63cca82ff37b", "size": 220333, "numPackages": 55}, "1725492213000": {"name": "/diff/1725492213000.json", "sha256": "7aa22b070d9f6f77fd069cab7fdbb38aa9f734d01982d9b9fadb3560807367ff", "size": 218833, "numPackages": 55}, "1725558218000": {"name": "/diff/1725558218000.json", "sha256": "cfae51610c44ec8dd73f390f7af46f71ebf4b2233151ec2f40f8c403775d815b", "size": 208567, "numPackages": 54}, "1725581280000": {"name": "/diff/1725581280000.json", "sha256": "9c5e39cc363e2a98c35fab6ec389f6b1a272fb92298c8f7f8eb158ba5ad3f7b1", "size": 207136, "numPackages": 48}, "1725645028000": {"name": "/diff/1725645028000.json", "sha256": "996c8e982e21dbdbcf25424ea4d3f32a7b67f7eea249db2392ea31a2bef033f6", "size": 98678, "numPackages": 47}, "1725731263000": {"name": "/diff/1725731263000.json", "sha256": "5dd06ef6da469b3881933b076ca0d989372477300b1f43070ae6b041763539da", "size": 80050, "numPackages": 37}, "1725746579000": {"name": "/diff/1725746579000.json", "sha256": "8bb1c009b828a3cecaa8180c08ac7a81b51c2d8b036566ec08fb7159dc61127a", "size": 58098, "numPackages": 31}, "1725807608000": {"name": "/diff/1725807608000.json", "sha256": "95ffb733c6e1e839f18c90e1cc704e554b0ae0eb26b52f0cf6437ee7a91ec96e", "size": 53358, "numPackages": 30}, "1725817837000": {"name": "/diff/1725817837000.json", "sha256": "21fed03d9e1b89cc2c4753084bcf49b681b4e4219375d9fdb5db1dd48a9a2fd3", "size": 16366, "numPackages": 28}, "1725885326000": {"name": "/diff/1725885326000.json", "sha256": "f2f22d1a56262276e07c68d5d71a149a50ddfa8c47b82bb3b63e0077f58121b6", "size": 13324, "numPackages": 9}}}
|
||||||
BIN
app/src/androidTest/assets/izzy_index_v1.jar
Normal file
BIN
app/src/androidTest/assets/izzy_index_v1.jar
Normal file
Binary file not shown.
1
app/src/androidTest/assets/izzy_index_v1.json
Normal file
1
app/src/androidTest/assets/izzy_index_v1.json
Normal file
File diff suppressed because one or more lines are too long
1
app/src/androidTest/assets/izzy_index_v2.json
Normal file
1
app/src/androidTest/assets/izzy_index_v2.json
Normal file
File diff suppressed because one or more lines are too long
1
app/src/androidTest/assets/izzy_index_v2_updated.json
Normal file
1
app/src/androidTest/assets/izzy_index_v2_updated.json
Normal file
File diff suppressed because one or more lines are too long
@@ -0,0 +1,92 @@
|
|||||||
|
package com.looker.droidify.index
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.filters.SmallTest
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import com.looker.droidify.model.Repository
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import java.io.File
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
import kotlin.system.measureTimeMillis
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
@SmallTest
|
||||||
|
class RepositoryUpdaterTest {
|
||||||
|
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var repository: Repository
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setup() {
|
||||||
|
context = InstrumentationRegistry.getInstrumentation().context
|
||||||
|
repository = Repository(
|
||||||
|
id = 15,
|
||||||
|
address = "https://apt.izzysoft.de/fdroid/repo",
|
||||||
|
mirrors = emptyList(),
|
||||||
|
name = "IzzyOnDroid F-Droid Repo",
|
||||||
|
description = "",
|
||||||
|
version = 20002,
|
||||||
|
enabled = true,
|
||||||
|
fingerprint = "3BF0D6ABFEAE2F401707B6D966BE743BF0EEE49C2561B9BA39073711F628937A",
|
||||||
|
lastModified = "",
|
||||||
|
entityTag = "",
|
||||||
|
updated = 1735315749835,
|
||||||
|
timestamp = 1725352450000,
|
||||||
|
authentication = "",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun processFile() {
|
||||||
|
testRepetition(1) {
|
||||||
|
val createFile = File.createTempFile("index", "entry")
|
||||||
|
val mergerFile = File.createTempFile("index", "merger")
|
||||||
|
val jarStream = context.resources.assets.open("index-v1.jar")
|
||||||
|
jarStream.copyTo(createFile.outputStream())
|
||||||
|
process(createFile, mergerFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun process(file: File, merger: File) = measureTimeMillis {
|
||||||
|
RepositoryUpdater.processFile(
|
||||||
|
context = context,
|
||||||
|
repository = repository,
|
||||||
|
indexType = RepositoryUpdater.IndexType.INDEX_V1,
|
||||||
|
unstable = false,
|
||||||
|
file = file,
|
||||||
|
mergerFile = merger,
|
||||||
|
lastModified = "",
|
||||||
|
entityTag = "",
|
||||||
|
callback = { stage, current, total ->
|
||||||
|
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun testRepetition(repetition: Int, block: () -> Long) {
|
||||||
|
val times = (1..repetition).map {
|
||||||
|
System.gc()
|
||||||
|
System.runFinalization()
|
||||||
|
block().toDouble()
|
||||||
|
}
|
||||||
|
val meanAndDeviation = times.culledMeanAndDeviation()
|
||||||
|
println(times)
|
||||||
|
println("${meanAndDeviation.first} ± ${meanAndDeviation.second}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun List<Double>.culledMeanAndDeviation(): Pair<Double, Double> = when {
|
||||||
|
isEmpty() -> Double.NaN to Double.NaN
|
||||||
|
size == 1 || size == 2 -> this.meanAndDeviation()
|
||||||
|
else -> sorted().subList(1, size - 1).meanAndDeviation()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun List<Double>.meanAndDeviation(): Pair<Double, Double> {
|
||||||
|
val mean = average()
|
||||||
|
return mean to sqrt(fold(0.0) { acc, value -> acc + (value - mean).squared() } / size)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Double.squared() = this * this
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.looker.droidify.sync
|
||||||
|
|
||||||
|
import com.looker.droidify.network.Downloader
|
||||||
|
import com.looker.droidify.network.NetworkResponse
|
||||||
|
import com.looker.droidify.network.ProgressListener
|
||||||
|
import com.looker.droidify.network.header.HeadersBuilder
|
||||||
|
import com.looker.droidify.network.validation.FileValidator
|
||||||
|
import com.looker.droidify.sync.common.assets
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.net.Proxy
|
||||||
|
|
||||||
|
val FakeDownloader = object : Downloader {
|
||||||
|
override fun setProxy(proxy: Proxy) {
|
||||||
|
TODO("Not yet implemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun headCall(
|
||||||
|
url: String,
|
||||||
|
headers: HeadersBuilder.() -> Unit
|
||||||
|
): NetworkResponse {
|
||||||
|
TODO("Not yet implemented")
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun downloadToFile(
|
||||||
|
url: String,
|
||||||
|
target: File,
|
||||||
|
validator: FileValidator?,
|
||||||
|
headers: HeadersBuilder.() -> Unit,
|
||||||
|
block: ProgressListener?
|
||||||
|
): NetworkResponse {
|
||||||
|
return if (url.endsWith("fail")) NetworkResponse.Error.Unknown(Exception("You asked for it"))
|
||||||
|
else {
|
||||||
|
val index = when {
|
||||||
|
url.endsWith("fdroid-index-v1.jar") -> assets("fdroid_index_v1.jar")
|
||||||
|
url.endsWith("fdroid-index-v1.json") -> assets("fdroid_index_v1.json")
|
||||||
|
url.endsWith("fdroid-index-v2.json") -> assets("fdroid_index_v2.json")
|
||||||
|
url.endsWith("index-v1.jar") -> assets("izzy_index_v1.jar")
|
||||||
|
url.endsWith("index-v2.json") -> assets("izzy_index_v2.json")
|
||||||
|
url.endsWith("index-v2-updated.json") -> assets("izzy_index_v2_updated.json")
|
||||||
|
url.endsWith("entry.jar") -> assets("izzy_entry.jar")
|
||||||
|
url.endsWith("/diff/1725731263000.json") -> assets("izzy_diff.json")
|
||||||
|
// Just in case we try these in future
|
||||||
|
url.endsWith("index-v1.json") -> assets("izzy_index_v1.json")
|
||||||
|
url.endsWith("entry.json") -> assets("izzy_entry.json")
|
||||||
|
else -> error("Unknown URL: $url")
|
||||||
|
}
|
||||||
|
index.writeTo(target)
|
||||||
|
NetworkResponse.Success(200, null, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend infix fun InputStream.writeTo(file: File) = withContext(Dispatchers.IO) {
|
||||||
|
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||||
|
var bytesRead = read(buffer)
|
||||||
|
file.outputStream().use { output ->
|
||||||
|
while (bytesRead != -1) {
|
||||||
|
ensureActive()
|
||||||
|
output.write(buffer, 0, bytesRead)
|
||||||
|
bytesRead = read(buffer)
|
||||||
|
}
|
||||||
|
output.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package com.looker.droidify.sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import com.looker.droidify.domain.model.Repo
|
||||||
|
import com.looker.droidify.sync.common.IndexJarValidator
|
||||||
|
import com.looker.droidify.sync.common.Izzy
|
||||||
|
import com.looker.droidify.sync.common.JsonParser
|
||||||
|
import com.looker.droidify.sync.common.assets
|
||||||
|
import com.looker.droidify.sync.common.downloadIndex
|
||||||
|
import com.looker.droidify.sync.common.benchmark
|
||||||
|
import com.looker.droidify.sync.v2.EntryParser
|
||||||
|
import com.looker.droidify.sync.v2.EntrySyncable
|
||||||
|
import com.looker.droidify.sync.v2.model.Entry
|
||||||
|
import com.looker.droidify.sync.v2.model.IndexV2
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import kotlinx.serialization.ExperimentalSerializationApi
|
||||||
|
import kotlinx.serialization.json.decodeFromStream
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import kotlin.system.measureTimeMillis
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class EntrySyncableTest {
|
||||||
|
|
||||||
|
private lateinit var dispatcher: CoroutineDispatcher
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var syncable: Syncable<Entry>
|
||||||
|
private lateinit var parser: Parser<Entry>
|
||||||
|
private lateinit var validator: IndexValidator
|
||||||
|
private lateinit var repo: Repo
|
||||||
|
private lateinit var newIndex: IndexV2
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In this particular test 1 package is removed and 36 packages are updated
|
||||||
|
*/
|
||||||
|
|
||||||
|
@OptIn(ExperimentalSerializationApi::class)
|
||||||
|
@Before
|
||||||
|
fun before() {
|
||||||
|
context = InstrumentationRegistry.getInstrumentation().context
|
||||||
|
dispatcher = StandardTestDispatcher()
|
||||||
|
validator = IndexJarValidator(dispatcher)
|
||||||
|
parser = EntryParser(dispatcher, JsonParser, validator)
|
||||||
|
syncable = EntrySyncable(context, FakeDownloader, dispatcher)
|
||||||
|
newIndex = JsonParser.decodeFromStream<IndexV2>(assets("izzy_index_v2_updated.json"))
|
||||||
|
repo = Izzy
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun benchmark_sync_full() = runTest(dispatcher) {
|
||||||
|
val output = benchmark(10) {
|
||||||
|
measureTimeMillis { syncable.sync(repo) }
|
||||||
|
}
|
||||||
|
println(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun benchmark_entry_parser() = runTest(dispatcher) {
|
||||||
|
val output = benchmark(10) {
|
||||||
|
measureTimeMillis {
|
||||||
|
parser.parse(
|
||||||
|
file = FakeDownloader.downloadIndex(
|
||||||
|
context = context,
|
||||||
|
repo = repo,
|
||||||
|
fileName = "izzy",
|
||||||
|
url = "entry.jar"
|
||||||
|
),
|
||||||
|
repo = repo
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun check_if_patch_applies() = runTest(dispatcher) {
|
||||||
|
// Downloads old index file as the index file does not exist
|
||||||
|
val (fingerprint1, index1) = syncable.sync(repo)
|
||||||
|
assert(index1 != null)
|
||||||
|
// Downloads the diff as the index file exists and is older than entry version
|
||||||
|
val (fingerprint2, index2) = syncable.sync(
|
||||||
|
repo.copy(
|
||||||
|
versionInfo = repo.versionInfo.copy(
|
||||||
|
timestamp = index1!!.repo.timestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert(index2 != null)
|
||||||
|
// Does not download anything
|
||||||
|
val (fingerprint3, index3) = syncable.sync(
|
||||||
|
repo.copy(
|
||||||
|
versionInfo = repo.versionInfo.copy(
|
||||||
|
timestamp = index2!!.repo.timestamp
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert(index3 == null)
|
||||||
|
|
||||||
|
// Check if all the packages are same
|
||||||
|
assertContentEquals(newIndex.packages.keys.sorted(), index2.packages.keys.sorted())
|
||||||
|
// Check if all the version hashes are same
|
||||||
|
assertContentEquals(
|
||||||
|
newIndex.packages.values.flatMap { it.versions.keys }.sorted(),
|
||||||
|
index2.packages.values.flatMap { it.versions.keys }.sorted(),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Check if repo antifeatures are same
|
||||||
|
assertContentEquals(
|
||||||
|
newIndex.repo.antiFeatures.keys.sorted(),
|
||||||
|
index2.repo.antiFeatures.keys.sorted()
|
||||||
|
)
|
||||||
|
|
||||||
|
// Check if repo categories are same
|
||||||
|
assertContentEquals(
|
||||||
|
newIndex.repo.categories.keys.sorted(),
|
||||||
|
index2.repo.categories.keys.sorted()
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(fingerprint1, fingerprint2)
|
||||||
|
assertEquals(fingerprint2, fingerprint3)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.looker.droidify.sync
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.Fingerprint
|
||||||
|
import java.util.jar.JarEntry
|
||||||
|
|
||||||
|
val FakeIndexValidator = object : IndexValidator {
|
||||||
|
override suspend fun validate(
|
||||||
|
jarEntry: JarEntry,
|
||||||
|
expectedFingerprint: Fingerprint?
|
||||||
|
): Fingerprint {
|
||||||
|
return expectedFingerprint ?: Fingerprint("0".repeat(64))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
package com.looker.droidify.sync
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import com.looker.droidify.domain.model.Repo
|
||||||
|
import com.looker.droidify.sync.common.IndexJarValidator
|
||||||
|
import com.looker.droidify.sync.common.Izzy
|
||||||
|
import com.looker.droidify.sync.common.JsonParser
|
||||||
|
import com.looker.droidify.sync.common.downloadIndex
|
||||||
|
import com.looker.droidify.sync.common.benchmark
|
||||||
|
import com.looker.droidify.sync.common.toV2
|
||||||
|
import com.looker.droidify.sync.v1.V1Parser
|
||||||
|
import com.looker.droidify.sync.v1.V1Syncable
|
||||||
|
import com.looker.droidify.sync.v1.model.IndexV1
|
||||||
|
import com.looker.droidify.sync.v2.V2Parser
|
||||||
|
import com.looker.droidify.sync.v2.model.FileV2
|
||||||
|
import com.looker.droidify.sync.v2.model.IndexV2
|
||||||
|
import com.looker.droidify.sync.v2.model.MetadataV2
|
||||||
|
import com.looker.droidify.sync.v2.model.VersionV2
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
import kotlin.system.measureTimeMillis
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContentEquals
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
|
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
class V1SyncableTest {
|
||||||
|
|
||||||
|
private lateinit var dispatcher: CoroutineDispatcher
|
||||||
|
private lateinit var context: Context
|
||||||
|
private lateinit var syncable: Syncable<IndexV1>
|
||||||
|
private lateinit var parser: Parser<IndexV1>
|
||||||
|
private lateinit var v2Parser: Parser<IndexV2>
|
||||||
|
private lateinit var validator: IndexValidator
|
||||||
|
private lateinit var repo: Repo
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun before() {
|
||||||
|
context = InstrumentationRegistry.getInstrumentation().context
|
||||||
|
dispatcher = StandardTestDispatcher()
|
||||||
|
validator = IndexJarValidator(dispatcher)
|
||||||
|
parser = V1Parser(dispatcher, JsonParser, validator)
|
||||||
|
v2Parser = V2Parser(dispatcher, JsonParser)
|
||||||
|
syncable = V1Syncable(context, FakeDownloader, dispatcher)
|
||||||
|
repo = Izzy
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun benchmark_sync_v1() = runTest(dispatcher) {
|
||||||
|
val output = benchmark(10) {
|
||||||
|
measureTimeMillis { syncable.sync(repo) }
|
||||||
|
}
|
||||||
|
println(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun benchmark_v1_parser() = runTest(dispatcher) {
|
||||||
|
val file = FakeDownloader.downloadIndex(context, repo, "izzy", "index-v1.jar")
|
||||||
|
val output = benchmark(10) {
|
||||||
|
measureTimeMillis {
|
||||||
|
parser.parse(
|
||||||
|
file = file,
|
||||||
|
repo = repo
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun benchmark_v1_vs_v2_parser() = runTest(dispatcher) {
|
||||||
|
val v1File = FakeDownloader.downloadIndex(context, repo, "izzy-v1", "index-v1.jar")
|
||||||
|
val v2File = FakeDownloader.downloadIndex(context, repo, "izzy-v2", "index-v2.json")
|
||||||
|
val output1 = benchmark(10) {
|
||||||
|
measureTimeMillis {
|
||||||
|
parser.parse(
|
||||||
|
file = v1File,
|
||||||
|
repo = repo
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val output2 = benchmark(10) {
|
||||||
|
measureTimeMillis {
|
||||||
|
parser.parse(
|
||||||
|
file = v2File,
|
||||||
|
repo = repo,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println(output1)
|
||||||
|
println(output2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun v1tov2() = runTest(dispatcher) {
|
||||||
|
testIndexConversion("index-v1.jar", "index-v2-updated.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Test
|
||||||
|
fun v1tov2FDroidRepo() = runTest(dispatcher) {
|
||||||
|
testIndexConversion("fdroid-index-v1.jar", "fdroid-index-v2.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun testIndexConversion(
|
||||||
|
v1: String,
|
||||||
|
v2: String,
|
||||||
|
targeted: String? = null,
|
||||||
|
) {
|
||||||
|
val fileV1 = FakeDownloader.downloadIndex(context, repo, "data-v1", v1)
|
||||||
|
val fileV2 = FakeDownloader.downloadIndex(context, repo, "data-v2", v2)
|
||||||
|
val (fingerV1, foundIndexV1) = parser.parse(fileV1, repo)
|
||||||
|
val (fingerV2, expectedIndex) = v2Parser.parse(fileV2, repo)
|
||||||
|
val foundIndex = foundIndexV1.toV2()
|
||||||
|
assertEquals(fingerV2, fingerV1)
|
||||||
|
assertNotNull(foundIndex)
|
||||||
|
assertNotNull(expectedIndex)
|
||||||
|
assertEquals(expectedIndex.repo.timestamp, foundIndex.repo.timestamp)
|
||||||
|
assertEquals(expectedIndex.packages.size, foundIndex.packages.size)
|
||||||
|
assertContentEquals(
|
||||||
|
expectedIndex.packages.keys.sorted(),
|
||||||
|
foundIndex.packages.keys.sorted(),
|
||||||
|
)
|
||||||
|
if (targeted == null) {
|
||||||
|
expectedIndex.packages.keys.forEach { key ->
|
||||||
|
val expectedPackage = expectedIndex.packages[key]
|
||||||
|
val foundPackage = foundIndex.packages[key]
|
||||||
|
|
||||||
|
println("**".repeat(25))
|
||||||
|
println("Testing: ${expectedPackage?.metadata?.name?.get("en-US")} <$key>")
|
||||||
|
|
||||||
|
assertNotNull(expectedPackage)
|
||||||
|
assertNotNull(foundPackage)
|
||||||
|
assertMetadata(expectedPackage.metadata, foundPackage.metadata)
|
||||||
|
assertVersion(expectedPackage.versions, foundPackage.versions)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val expectedPackage = expectedIndex.packages[targeted]
|
||||||
|
val foundPackage = foundIndex.packages[targeted]
|
||||||
|
|
||||||
|
println("**".repeat(25))
|
||||||
|
println("Testing: ${expectedPackage?.metadata?.name?.get("en-US")} <$targeted>")
|
||||||
|
|
||||||
|
assertNotNull(expectedPackage)
|
||||||
|
assertNotNull(foundPackage)
|
||||||
|
assertMetadata(expectedPackage.metadata, foundPackage.metadata)
|
||||||
|
assertVersion(expectedPackage.versions, foundPackage.versions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Cannot assert following:
|
||||||
|
* - `name` => because fdroidserver behaves weirdly
|
||||||
|
* */
|
||||||
|
private fun assertMetadata(expectedMetaData: MetadataV2, foundMetadata: MetadataV2) {
|
||||||
|
assertEquals(expectedMetaData.preferredSigner, foundMetadata.preferredSigner)
|
||||||
|
// assertLocalizedString(expectedMetaData.name, foundMetadata.name)
|
||||||
|
assertLocalizedString(expectedMetaData.summary, foundMetadata.summary)
|
||||||
|
assertLocalizedString(expectedMetaData.description, foundMetadata.description)
|
||||||
|
assertContentEquals(expectedMetaData.categories, foundMetadata.categories)
|
||||||
|
// Update
|
||||||
|
assertEquals(expectedMetaData.changelog, foundMetadata.changelog)
|
||||||
|
assertEquals(expectedMetaData.added, foundMetadata.added)
|
||||||
|
assertEquals(expectedMetaData.lastUpdated, foundMetadata.lastUpdated)
|
||||||
|
// Author
|
||||||
|
assertEquals(expectedMetaData.authorEmail, foundMetadata.authorEmail)
|
||||||
|
assertEquals(expectedMetaData.authorName, foundMetadata.authorName)
|
||||||
|
assertEquals(expectedMetaData.authorPhone, foundMetadata.authorPhone)
|
||||||
|
assertEquals(expectedMetaData.authorWebSite, foundMetadata.authorWebSite)
|
||||||
|
// Donate
|
||||||
|
assertEquals(expectedMetaData.bitcoin, foundMetadata.bitcoin)
|
||||||
|
assertEquals(expectedMetaData.liberapay, foundMetadata.liberapay)
|
||||||
|
assertEquals(expectedMetaData.flattrID, foundMetadata.flattrID)
|
||||||
|
assertEquals(expectedMetaData.openCollective, foundMetadata.openCollective)
|
||||||
|
assertEquals(expectedMetaData.litecoin, foundMetadata.litecoin)
|
||||||
|
assertContentEquals(expectedMetaData.donate, foundMetadata.donate)
|
||||||
|
// Source
|
||||||
|
assertEquals(expectedMetaData.translation, foundMetadata.translation)
|
||||||
|
assertEquals(expectedMetaData.issueTracker, foundMetadata.issueTracker)
|
||||||
|
assertEquals(expectedMetaData.license, foundMetadata.license)
|
||||||
|
assertEquals(expectedMetaData.sourceCode, foundMetadata.sourceCode)
|
||||||
|
// Graphics
|
||||||
|
assertLocalizedString(expectedMetaData.video, foundMetadata.video)
|
||||||
|
assertLocalized(expectedMetaData.icon, foundMetadata.icon) { expected, found ->
|
||||||
|
assertEquals(expected.name, found.name)
|
||||||
|
}
|
||||||
|
assertLocalized(expectedMetaData.promoGraphic, foundMetadata.promoGraphic) { expected, found ->
|
||||||
|
assertEquals(expected.name, found.name)
|
||||||
|
}
|
||||||
|
assertLocalized(expectedMetaData.tvBanner, foundMetadata.tvBanner) { expected, found ->
|
||||||
|
assertEquals(expected.name, found.name)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.featureGraphic,
|
||||||
|
foundMetadata.featureGraphic
|
||||||
|
) { expected, found ->
|
||||||
|
assertEquals(expected.name, found.name)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.screenshots?.phone,
|
||||||
|
foundMetadata.screenshots?.phone
|
||||||
|
) { expected, found ->
|
||||||
|
assertFiles(expected, found)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.screenshots?.sevenInch,
|
||||||
|
foundMetadata.screenshots?.sevenInch
|
||||||
|
) { expected, found ->
|
||||||
|
assertFiles(expected, found)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.screenshots?.tenInch,
|
||||||
|
foundMetadata.screenshots?.tenInch
|
||||||
|
) { expected, found ->
|
||||||
|
assertFiles(expected, found)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.screenshots?.tv,
|
||||||
|
foundMetadata.screenshots?.tv
|
||||||
|
) { expected, found ->
|
||||||
|
assertFiles(expected, found)
|
||||||
|
}
|
||||||
|
assertLocalized(
|
||||||
|
expectedMetaData.screenshots?.wear,
|
||||||
|
foundMetadata.screenshots?.wear
|
||||||
|
) { expected, found ->
|
||||||
|
assertFiles(expected, found)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Cannot assert following:
|
||||||
|
* - `whatsNew` => we added same changelog to all versions
|
||||||
|
* - `antiFeatures` => anti features are now version specific
|
||||||
|
* */
|
||||||
|
private fun assertVersion(
|
||||||
|
expected: Map<String, VersionV2>,
|
||||||
|
found: Map<String, VersionV2>,
|
||||||
|
) {
|
||||||
|
assertEquals(expected.keys.size, found.keys.size)
|
||||||
|
assertContentEquals(expected.keys.sorted(), found.keys.sorted().asIterable())
|
||||||
|
expected.keys.forEach { versionHash ->
|
||||||
|
val expectedVersion = expected[versionHash]
|
||||||
|
val foundVersion = found[versionHash]
|
||||||
|
assertNotNull(expectedVersion)
|
||||||
|
assertNotNull(foundVersion)
|
||||||
|
|
||||||
|
assertEquals(expectedVersion.added, foundVersion.added)
|
||||||
|
assertEquals(expectedVersion.file.name, foundVersion.file.name)
|
||||||
|
assertEquals(expectedVersion.src?.name, foundVersion.src?.name)
|
||||||
|
|
||||||
|
val expectedMan = expectedVersion.manifest
|
||||||
|
val foundMan = foundVersion.manifest
|
||||||
|
|
||||||
|
assertEquals(expectedMan.versionCode, foundMan.versionCode)
|
||||||
|
assertEquals(expectedMan.versionName, foundMan.versionName)
|
||||||
|
assertEquals(expectedMan.maxSdkVersion, foundMan.maxSdkVersion)
|
||||||
|
assertEquals(expectedMan.usesSdk, foundMan.usesSdk)
|
||||||
|
|
||||||
|
assertContentEquals(
|
||||||
|
expectedMan.features.sortedBy { it.name },
|
||||||
|
foundMan.features.sortedBy { it.name },
|
||||||
|
)
|
||||||
|
assertContentEquals(expectedMan.usesPermission, foundMan.usesPermission)
|
||||||
|
assertContentEquals(expectedMan.usesPermissionSdk23, foundMan.usesPermissionSdk23)
|
||||||
|
assertContentEquals(expectedMan.signer?.sha256?.sorted(), foundMan.signer?.sha256?.sorted())
|
||||||
|
assertContentEquals(expectedMan.nativecode.sorted(), foundMan.nativecode.sorted())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun assertLocalizedString(
|
||||||
|
expected: Map<String, String>?,
|
||||||
|
found: Map<String, String>?,
|
||||||
|
message: String? = null,
|
||||||
|
) {
|
||||||
|
assertLocalized(expected, found) { one, two ->
|
||||||
|
assertEquals(one, two, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> assertLocalized(
|
||||||
|
expected: Map<String, T>?,
|
||||||
|
found: Map<String, T>?,
|
||||||
|
block: (expected: T, found: T) -> Unit,
|
||||||
|
) {
|
||||||
|
if (expected == null || found == null) {
|
||||||
|
assertEquals(expected, found)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
assertNotNull(expected)
|
||||||
|
assertNotNull(found)
|
||||||
|
assertEquals(expected.size, found.size)
|
||||||
|
assertContentEquals(expected.keys.sorted(), found.keys.sorted().asIterable())
|
||||||
|
expected.keys.forEach {
|
||||||
|
if (expected[it] != null && found[it] != null) block(expected[it]!!, found[it]!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun assertFiles(expected: List<FileV2>, found: List<FileV2>, message: String? = null) {
|
||||||
|
// Only check name, because we cannot add sha to old index
|
||||||
|
assertContentEquals(expected.map { it.name }, found.map { it.name }.asIterable(), message)
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.looker.droidify.sync.common
|
||||||
|
|
||||||
|
import kotlin.math.pow
|
||||||
|
import kotlin.math.sqrt
|
||||||
|
|
||||||
|
internal inline fun benchmark(
|
||||||
|
repetition: Int,
|
||||||
|
extraMessage: String? = null,
|
||||||
|
block: () -> Long,
|
||||||
|
): String {
|
||||||
|
if (extraMessage != null) {
|
||||||
|
println("=".repeat(50))
|
||||||
|
println(extraMessage)
|
||||||
|
println("=".repeat(50))
|
||||||
|
}
|
||||||
|
val times = DoubleArray(repetition)
|
||||||
|
repeat(repetition) { iteration ->
|
||||||
|
System.gc()
|
||||||
|
System.runFinalization()
|
||||||
|
times[iteration] = block().toDouble()
|
||||||
|
}
|
||||||
|
val meanAndDeviation = times.culledMeanAndDeviation()
|
||||||
|
return buildString {
|
||||||
|
append("=".repeat(50))
|
||||||
|
append("\n")
|
||||||
|
append(times.joinToString(" | "))
|
||||||
|
append("\n")
|
||||||
|
append("${meanAndDeviation.first} ms ± ${meanAndDeviation.second.toFloat()} ms")
|
||||||
|
append("\n")
|
||||||
|
append("=".repeat(50))
|
||||||
|
append("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun DoubleArray.culledMeanAndDeviation(): Pair<Double, Double> {
|
||||||
|
sort()
|
||||||
|
return meanAndDeviation()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun DoubleArray.meanAndDeviation(): Pair<Double, Double> {
|
||||||
|
val mean = average()
|
||||||
|
return mean to sqrt(fold(0.0) { acc, value -> acc + (value - mean).pow(2) } / size)
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.looker.droidify.sync.common
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.Authentication
|
||||||
|
import com.looker.droidify.domain.model.Fingerprint
|
||||||
|
import com.looker.droidify.domain.model.Repo
|
||||||
|
import com.looker.droidify.domain.model.VersionInfo
|
||||||
|
|
||||||
|
val Izzy = Repo(
|
||||||
|
id = 1L,
|
||||||
|
enabled = true,
|
||||||
|
address = "https://apt.izzysoft.de/fdroid/repo",
|
||||||
|
name = "IzzyOnDroid F-Droid Repo",
|
||||||
|
description = "This is a repository of apps to be used with F-Droid. Applications in this repository are official binaries built by the original application developers, taken from their resp. repositories (mostly Github, GitLab, Codeberg). Updates for the apps are usually fetched daily, and you can expect daily index updates.",
|
||||||
|
fingerprint = Fingerprint("3BF0D6ABFEAE2F401707B6D966BE743BF0EEE49C2561B9BA39073711F628937A"),
|
||||||
|
authentication = Authentication("", ""),
|
||||||
|
versionInfo = VersionInfo(0L, null),
|
||||||
|
mirrors = emptyList(),
|
||||||
|
antiFeatures = emptyList(),
|
||||||
|
categories = emptyList(),
|
||||||
|
)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.looker.droidify.sync.common
|
||||||
|
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
fun assets(name: String): InputStream {
|
||||||
|
return InstrumentationRegistry.getInstrumentation().context.assets.open(name)
|
||||||
|
}
|
||||||
188
app/src/main/AndroidManifest.xml
Normal file
188
app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||||
|
<uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" />
|
||||||
|
<uses-permission android:name="android.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION" />
|
||||||
|
<uses-permission android:name="android.permission.ENFORCE_UPDATE_OWNERSHIP" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||||
|
tools:ignore="QueryAllPackagesPermission" />
|
||||||
|
|
||||||
|
<uses-feature
|
||||||
|
android:name="android.software.leanback"
|
||||||
|
android:required="false" />
|
||||||
|
<uses-feature
|
||||||
|
android:name="android.hardware.touchscreen"
|
||||||
|
android:required="false" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".Droidify"
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:banner="@drawable/tv_banner"
|
||||||
|
android:enableOnBackInvokedCallback="true"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="@string/application_name"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/MainTheme"
|
||||||
|
tools:ignore="UnusedAttribute">
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".Droidify$BootReceiver"
|
||||||
|
android:exported="true">
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.SHOW_APP_INFO" />
|
||||||
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data android:scheme="fdroid.app" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data
|
||||||
|
android:host="details"
|
||||||
|
android:scheme="market" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data android:scheme="http" />
|
||||||
|
<data android:scheme="https" />
|
||||||
|
<data android:host="f-droid.org" />
|
||||||
|
<data android:host="www.f-droid.org" />
|
||||||
|
<data android:host="staging.f-droid.org" />
|
||||||
|
<data android:pathPattern="/app/.*" />
|
||||||
|
<data android:pathPattern="/packages/.*" />
|
||||||
|
<data android:pathPattern="/.*/packages/.*" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data android:scheme="http" />
|
||||||
|
<data android:scheme="https" />
|
||||||
|
<data android:host="apt.izzysoft.de" />
|
||||||
|
<data android:pathPattern="/fdroid/index/apk/.*" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<intent-filter android:autoVerify="true">
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data android:scheme="https" />
|
||||||
|
<data android:host="droidify.eu.org" />
|
||||||
|
<data android:pathPattern="/app/.*" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
<!--Adding repo with special url-->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
|
<data android:scheme="fdroidrepo" />
|
||||||
|
<data android:scheme="fdroidrepos" />
|
||||||
|
</intent-filter>
|
||||||
|
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.SyncService"
|
||||||
|
android:foregroundServiceType="dataSync" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.SyncService$Job"
|
||||||
|
android:exported="false"
|
||||||
|
android:permission="android.permission.BIND_JOB_SERVICE" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.DownloadService"
|
||||||
|
android:foregroundServiceType="dataSync" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".installer.installers.session.SessionInstallerReceiver"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name="androidx.work.impl.foreground.SystemForegroundService"
|
||||||
|
android:foregroundServiceType="dataSync"
|
||||||
|
tools:node="merge" />
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name="androidx.appcompat.app.AppLocalesMetadataHolderService"
|
||||||
|
android:enabled="false"
|
||||||
|
android:exported="false">
|
||||||
|
<meta-data
|
||||||
|
android:name="autoStoreLocales"
|
||||||
|
android:value="true" />
|
||||||
|
</service>
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:name="rikka.shizuku.ShizukuProvider"
|
||||||
|
android:authorities="${applicationId}.shizuku"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true"
|
||||||
|
android:multiprocess="false"
|
||||||
|
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:name=".utility.common.cache.Cache$Provider"
|
||||||
|
android:authorities="${applicationId}.provider.cache"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true" />
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:name="androidx.startup.InitializationProvider"
|
||||||
|
android:authorities="${applicationId}.androidx-startup"
|
||||||
|
tools:node="remove" />
|
||||||
|
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
||||||
BIN
app/src/main/ic_launcher-playstore.png
Normal file
BIN
app/src/main/ic_launcher-playstore.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
267
app/src/main/kotlin/com/looker/droidify/Droidify.kt
Normal file
267
app/src/main/kotlin/com/looker/droidify/Droidify.kt
Normal file
@@ -0,0 +1,267 @@
|
|||||||
|
package com.looker.droidify
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.IntentFilter
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.StrictMode
|
||||||
|
import androidx.annotation.RequiresApi
|
||||||
|
import androidx.appcompat.app.AppCompatDelegate
|
||||||
|
import androidx.hilt.work.HiltWorkerFactory
|
||||||
|
import androidx.work.Configuration
|
||||||
|
import androidx.work.NetworkType
|
||||||
|
import coil3.ImageLoader
|
||||||
|
import coil3.PlatformContext
|
||||||
|
import coil3.SingletonImageLoader
|
||||||
|
import coil3.asImage
|
||||||
|
import coil3.disk.DiskCache
|
||||||
|
import coil3.disk.directory
|
||||||
|
import coil3.memory.MemoryCache
|
||||||
|
import coil3.request.crossfade
|
||||||
|
import com.looker.droidify.content.ProductPreferences
|
||||||
|
import com.looker.droidify.database.Database
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.datastore.get
|
||||||
|
import com.looker.droidify.datastore.model.AutoSync
|
||||||
|
import com.looker.droidify.datastore.model.ProxyPreference
|
||||||
|
import com.looker.droidify.datastore.model.ProxyType
|
||||||
|
import com.looker.droidify.index.RepositoryUpdater
|
||||||
|
import com.looker.droidify.installer.InstallManager
|
||||||
|
import com.looker.droidify.network.Downloader
|
||||||
|
import com.looker.droidify.receivers.InstalledAppReceiver
|
||||||
|
import com.looker.droidify.service.Connection
|
||||||
|
import com.looker.droidify.service.SyncService
|
||||||
|
import com.looker.droidify.sync.SyncPreference
|
||||||
|
import com.looker.droidify.sync.toJobNetworkType
|
||||||
|
import com.looker.droidify.utility.common.Constants
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.extension.getDrawableCompat
|
||||||
|
import com.looker.droidify.utility.common.extension.getInstalledPackagesCompat
|
||||||
|
import com.looker.droidify.utility.common.extension.jobScheduler
|
||||||
|
import com.looker.droidify.utility.common.log
|
||||||
|
import com.looker.droidify.utility.extension.toInstalledItem
|
||||||
|
import com.looker.droidify.work.CleanUpWorker
|
||||||
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.flow.collectIndexed
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Proxy
|
||||||
|
import javax.inject.Inject
|
||||||
|
import kotlin.time.Duration.Companion.INFINITE
|
||||||
|
import kotlin.time.Duration.Companion.hours
|
||||||
|
|
||||||
|
@HiltAndroidApp
|
||||||
|
class Droidify : Application(), SingletonImageLoader.Factory, Configuration.Provider {
|
||||||
|
|
||||||
|
private val parentJob = SupervisorJob()
|
||||||
|
private val appScope = CoroutineScope(Dispatchers.Default + parentJob)
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var settingsRepository: SettingsRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var installer: InstallManager
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var downloader: Downloader
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var workerFactory: HiltWorkerFactory
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
|
||||||
|
if (BuildConfig.DEBUG && SdkCheck.isOreo) strictThreadPolicy()
|
||||||
|
|
||||||
|
val databaseUpdated = Database.init(this)
|
||||||
|
ProductPreferences.init(this, appScope)
|
||||||
|
RepositoryUpdater.init(appScope, downloader)
|
||||||
|
listenApplications()
|
||||||
|
checkLanguage()
|
||||||
|
updatePreference()
|
||||||
|
appScope.launch { installer() }
|
||||||
|
|
||||||
|
if (databaseUpdated) forceSyncAll()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onTerminate() {
|
||||||
|
super.onTerminate()
|
||||||
|
appScope.cancel("Application Terminated")
|
||||||
|
installer.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun listenApplications() {
|
||||||
|
appScope.launch(Dispatchers.Default) {
|
||||||
|
registerReceiver(
|
||||||
|
InstalledAppReceiver(packageManager),
|
||||||
|
IntentFilter().apply {
|
||||||
|
addAction(Intent.ACTION_PACKAGE_ADDED)
|
||||||
|
addAction(Intent.ACTION_PACKAGE_REMOVED)
|
||||||
|
addDataScheme("package")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
val installedItems =
|
||||||
|
packageManager.getInstalledPackagesCompat()
|
||||||
|
?.map { it.toInstalledItem() }
|
||||||
|
?: return@launch
|
||||||
|
Database.InstalledAdapter.putAll(installedItems)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun checkLanguage() {
|
||||||
|
appScope.launch {
|
||||||
|
val lastSetLanguage = settingsRepository.getInitial().language
|
||||||
|
val systemSetLanguage = AppCompatDelegate.getApplicationLocales().toLanguageTags()
|
||||||
|
if (systemSetLanguage != lastSetLanguage && lastSetLanguage != "system") {
|
||||||
|
settingsRepository.setLanguage(systemSetLanguage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updatePreference() {
|
||||||
|
appScope.launch {
|
||||||
|
launch {
|
||||||
|
settingsRepository.get { unstableUpdate }.drop(1).collect {
|
||||||
|
forceSyncAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
settingsRepository.get { autoSync }.collectIndexed { index, syncMode ->
|
||||||
|
// Don't update sync job on initial collect
|
||||||
|
updateSyncJob(index > 0, syncMode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
settingsRepository.get { cleanUpInterval }.drop(1).collect {
|
||||||
|
if (it == INFINITE) {
|
||||||
|
CleanUpWorker.removeAllSchedules(applicationContext)
|
||||||
|
} else {
|
||||||
|
CleanUpWorker.scheduleCleanup(applicationContext, it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
launch {
|
||||||
|
settingsRepository.get { proxy }.collect(::updateProxy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateProxy(proxyPreference: ProxyPreference) {
|
||||||
|
val type = proxyPreference.type
|
||||||
|
val host = proxyPreference.host
|
||||||
|
val port = proxyPreference.port
|
||||||
|
val socketAddress = when (type) {
|
||||||
|
ProxyType.DIRECT -> null
|
||||||
|
ProxyType.HTTP, ProxyType.SOCKS -> {
|
||||||
|
try {
|
||||||
|
InetSocketAddress.createUnresolved(host, port)
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
log(e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val androidProxyType = when (type) {
|
||||||
|
ProxyType.DIRECT -> Proxy.Type.DIRECT
|
||||||
|
ProxyType.HTTP -> Proxy.Type.HTTP
|
||||||
|
ProxyType.SOCKS -> Proxy.Type.SOCKS
|
||||||
|
}
|
||||||
|
val determinedProxy = socketAddress?.let { Proxy(androidProxyType, it) } ?: Proxy.NO_PROXY
|
||||||
|
downloader.setProxy(determinedProxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateSyncJob(force: Boolean, autoSync: AutoSync) {
|
||||||
|
if (autoSync == AutoSync.NEVER) {
|
||||||
|
jobScheduler?.cancel(Constants.JOB_ID_SYNC)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val jobScheduler = jobScheduler
|
||||||
|
val syncConditions = when (autoSync) {
|
||||||
|
AutoSync.ALWAYS -> SyncPreference(NetworkType.CONNECTED)
|
||||||
|
AutoSync.WIFI_ONLY -> SyncPreference(NetworkType.UNMETERED)
|
||||||
|
AutoSync.WIFI_PLUGGED_IN -> SyncPreference(NetworkType.UNMETERED, pluggedIn = true)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
val isCompleted = jobScheduler?.allPendingJobs
|
||||||
|
?.any { it.id == Constants.JOB_ID_SYNC } == false
|
||||||
|
if ((force || isCompleted) && syncConditions != null) {
|
||||||
|
val period = 12.hours.inWholeMilliseconds
|
||||||
|
val job = SyncService.Job.create(
|
||||||
|
context = this,
|
||||||
|
periodMillis = period,
|
||||||
|
networkType = syncConditions.toJobNetworkType(),
|
||||||
|
isCharging = syncConditions.pluggedIn,
|
||||||
|
isBatteryLow = syncConditions.batteryNotLow
|
||||||
|
)
|
||||||
|
jobScheduler?.schedule(job)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun forceSyncAll() {
|
||||||
|
Database.RepositoryAdapter.getAll().forEach {
|
||||||
|
if (it.lastModified.isNotEmpty() || it.entityTag.isNotEmpty()) {
|
||||||
|
Database.RepositoryAdapter.put(it.copy(lastModified = "", entityTag = ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Connection(SyncService::class.java, onBind = { connection, binder ->
|
||||||
|
binder.sync(SyncService.SyncRequest.FORCE)
|
||||||
|
connection.unbind(this)
|
||||||
|
}).bind(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
@SuppressLint("UnsafeProtectedBroadcastReceiver")
|
||||||
|
override fun onReceive(context: Context, intent: Intent) = Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
override val workManagerConfiguration: Configuration
|
||||||
|
get() = Configuration.Builder()
|
||||||
|
.setWorkerFactory(workerFactory)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
override fun newImageLoader(context: PlatformContext): ImageLoader {
|
||||||
|
val memoryCache = MemoryCache.Builder()
|
||||||
|
.maxSizePercent(context, 0.25)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val diskCache = DiskCache.Builder()
|
||||||
|
.directory(Cache.getImagesDir(this))
|
||||||
|
.maxSizePercent(0.05)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
return ImageLoader.Builder(this)
|
||||||
|
.memoryCache(memoryCache)
|
||||||
|
.diskCache(diskCache)
|
||||||
|
.error(getDrawableCompat(R.drawable.ic_cannot_load).asImage())
|
||||||
|
.crossfade(350)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequiresApi(Build.VERSION_CODES.O)
|
||||||
|
fun strictThreadPolicy() {
|
||||||
|
StrictMode.setThreadPolicy(
|
||||||
|
StrictMode.ThreadPolicy.Builder()
|
||||||
|
.detectDiskReads()
|
||||||
|
.detectDiskWrites()
|
||||||
|
.detectNetwork()
|
||||||
|
.detectUnbufferedIo()
|
||||||
|
.penaltyLog()
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
StrictMode.setVmPolicy(
|
||||||
|
StrictMode.VmPolicy.Builder()
|
||||||
|
.detectAll()
|
||||||
|
.penaltyLog()
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
}
|
||||||
307
app/src/main/kotlin/com/looker/droidify/MainActivity.kt
Normal file
307
app/src/main/kotlin/com/looker/droidify/MainActivity.kt
Normal file
@@ -0,0 +1,307 @@
|
|||||||
|
package com.looker.droidify
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Parcelable
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import androidx.activity.OnBackPressedCallback
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.appcompat.widget.Toolbar
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import androidx.fragment.app.commit
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import com.looker.droidify.utility.common.DeeplinkType
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.deeplinkType
|
||||||
|
import com.looker.droidify.utility.common.extension.homeAsUp
|
||||||
|
import com.looker.droidify.utility.common.extension.inputManager
|
||||||
|
import com.looker.droidify.utility.common.getInstallPackageName
|
||||||
|
import com.looker.droidify.utility.common.requestNotificationPermission
|
||||||
|
import com.looker.droidify.database.CursorOwner
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.datastore.extension.getThemeRes
|
||||||
|
import com.looker.droidify.datastore.get
|
||||||
|
import com.looker.droidify.installer.InstallManager
|
||||||
|
import com.looker.droidify.installer.model.installFrom
|
||||||
|
import com.looker.droidify.ui.appDetail.AppDetailFragment
|
||||||
|
import com.looker.droidify.ui.favourites.FavouritesFragment
|
||||||
|
import com.looker.droidify.ui.repository.EditRepositoryFragment
|
||||||
|
import com.looker.droidify.ui.repository.RepositoriesFragment
|
||||||
|
import com.looker.droidify.ui.repository.RepositoryFragment
|
||||||
|
import com.looker.droidify.ui.settings.SettingsFragment
|
||||||
|
import com.looker.droidify.ui.tabsFragment.TabsFragment
|
||||||
|
import dagger.hilt.EntryPoint
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.parcelize.Parcelize
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class MainActivity : AppCompatActivity() {
|
||||||
|
companion object {
|
||||||
|
private const val STATE_FRAGMENT_STACK = "fragmentStack"
|
||||||
|
const val ACTION_UPDATES = "${BuildConfig.APPLICATION_ID}.intent.action.UPDATES"
|
||||||
|
const val ACTION_INSTALL = "${BuildConfig.APPLICATION_ID}.intent.action.INSTALL"
|
||||||
|
const val EXTRA_CACHE_FILE_NAME =
|
||||||
|
"${BuildConfig.APPLICATION_ID}.intent.extra.CACHE_FILE_NAME"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val notificationPermission =
|
||||||
|
registerForActivityResult(ActivityResultContracts.RequestPermission()) { }
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var installer: InstallManager
|
||||||
|
|
||||||
|
@Parcelize
|
||||||
|
private class FragmentStackItem(
|
||||||
|
val className: String, val arguments: Bundle?, val savedState: Fragment.SavedState?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
lateinit var cursorOwner: CursorOwner
|
||||||
|
private set
|
||||||
|
|
||||||
|
private var onBackPressedCallback: OnBackPressedCallback? = null
|
||||||
|
|
||||||
|
private val fragmentStack = mutableListOf<FragmentStackItem>()
|
||||||
|
|
||||||
|
private val currentFragment: Fragment?
|
||||||
|
get() {
|
||||||
|
supportFragmentManager.executePendingTransactions()
|
||||||
|
return supportFragmentManager.findFragmentById(R.id.main_content)
|
||||||
|
}
|
||||||
|
|
||||||
|
@EntryPoint
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
interface CustomUserRepositoryInjector {
|
||||||
|
fun settingsRepository(): SettingsRepository
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun collectChange() {
|
||||||
|
val hiltEntryPoint = EntryPointAccessors.fromApplication(
|
||||||
|
this, CustomUserRepositoryInjector::class.java
|
||||||
|
)
|
||||||
|
val newSettings = hiltEntryPoint.settingsRepository().get { theme to dynamicTheme }
|
||||||
|
runBlocking {
|
||||||
|
val theme = newSettings.first()
|
||||||
|
setTheme(
|
||||||
|
resources.configuration.getThemeRes(
|
||||||
|
theme = theme.first, dynamicTheme = theme.second
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
lifecycleScope.launch {
|
||||||
|
newSettings.drop(1).collect { themeAndDynamic ->
|
||||||
|
setTheme(
|
||||||
|
resources.configuration.getThemeRes(
|
||||||
|
theme = themeAndDynamic.first, dynamicTheme = themeAndDynamic.second
|
||||||
|
)
|
||||||
|
)
|
||||||
|
recreate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
collectChange()
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
val rootView = FrameLayout(this).apply { id = R.id.main_content }
|
||||||
|
addContentView(
|
||||||
|
rootView, ViewGroup.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
requestNotificationPermission(request = notificationPermission::launch)
|
||||||
|
|
||||||
|
supportFragmentManager.addFragmentOnAttachListener { _, _ ->
|
||||||
|
hideKeyboard()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (savedInstanceState == null) {
|
||||||
|
cursorOwner = CursorOwner()
|
||||||
|
supportFragmentManager.commit {
|
||||||
|
add(cursorOwner, CursorOwner::class.java.name)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cursorOwner =
|
||||||
|
supportFragmentManager.findFragmentByTag(CursorOwner::class.java.name) as CursorOwner
|
||||||
|
}
|
||||||
|
|
||||||
|
savedInstanceState?.getParcelableArrayList<FragmentStackItem>(STATE_FRAGMENT_STACK)
|
||||||
|
?.let { fragmentStack += it }
|
||||||
|
if (savedInstanceState == null) {
|
||||||
|
replaceFragment(TabsFragment(), null)
|
||||||
|
if ((intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
|
||||||
|
handleIntent(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (SdkCheck.isR) {
|
||||||
|
window.statusBarColor = resources.getColor(android.R.color.transparent, theme)
|
||||||
|
window.navigationBarColor = resources.getColor(android.R.color.transparent, theme)
|
||||||
|
WindowCompat.setDecorFitsSystemWindows(window, false)
|
||||||
|
}
|
||||||
|
backHandler()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
onBackPressedCallback = null
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onSaveInstanceState(outState: Bundle) {
|
||||||
|
super.onSaveInstanceState(outState)
|
||||||
|
outState.putParcelableArrayList(STATE_FRAGMENT_STACK, ArrayList(fragmentStack))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun backHandler() {
|
||||||
|
if (onBackPressedCallback == null) {
|
||||||
|
onBackPressedCallback = object : OnBackPressedCallback(enabled = false) {
|
||||||
|
override fun handleOnBackPressed() {
|
||||||
|
hideKeyboard()
|
||||||
|
popFragment()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
onBackPressedDispatcher.addCallback(
|
||||||
|
this,
|
||||||
|
onBackPressedCallback!!,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onBackPressedCallback?.isEnabled = fragmentStack.isNotEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun replaceFragment(fragment: Fragment, open: Boolean?) {
|
||||||
|
if (open != null) {
|
||||||
|
currentFragment?.view?.translationZ =
|
||||||
|
(if (open) Int.MIN_VALUE else Int.MAX_VALUE).toFloat()
|
||||||
|
}
|
||||||
|
supportFragmentManager.commit {
|
||||||
|
if (open != null) {
|
||||||
|
setCustomAnimations(
|
||||||
|
if (open) R.animator.slide_in else 0,
|
||||||
|
if (open) R.animator.slide_in_keep else R.animator.slide_out
|
||||||
|
)
|
||||||
|
}
|
||||||
|
setReorderingAllowed(true)
|
||||||
|
replace(R.id.main_content, fragment)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pushFragment(fragment: Fragment) {
|
||||||
|
currentFragment?.let {
|
||||||
|
fragmentStack.add(
|
||||||
|
FragmentStackItem(
|
||||||
|
it::class.java.name,
|
||||||
|
it.arguments,
|
||||||
|
supportFragmentManager.saveFragmentInstanceState(it)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
replaceFragment(fragment, true)
|
||||||
|
backHandler()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun popFragment(): Boolean {
|
||||||
|
return fragmentStack.isNotEmpty() && run {
|
||||||
|
val stackItem = fragmentStack.removeAt(fragmentStack.size - 1)
|
||||||
|
val fragment = Class.forName(stackItem.className).newInstance() as Fragment
|
||||||
|
stackItem.arguments?.let(fragment::setArguments)
|
||||||
|
stackItem.savedState?.let(fragment::setInitialSavedState)
|
||||||
|
replaceFragment(fragment, false)
|
||||||
|
backHandler()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hideKeyboard() {
|
||||||
|
inputManager?.hideSoftInputFromWindow((currentFocus ?: window.decorView).windowToken, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun onToolbarCreated(toolbar: Toolbar) {
|
||||||
|
if (fragmentStack.isNotEmpty()) {
|
||||||
|
toolbar.navigationIcon = toolbar.context.homeAsUp
|
||||||
|
toolbar.setNavigationOnClickListener { onBackPressedDispatcher.onBackPressed() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent)
|
||||||
|
handleIntent(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleIntent(intent: Intent?) {
|
||||||
|
when (intent?.action) {
|
||||||
|
ACTION_UPDATES -> {
|
||||||
|
if (currentFragment !is TabsFragment) {
|
||||||
|
fragmentStack.clear()
|
||||||
|
replaceFragment(TabsFragment(), true)
|
||||||
|
}
|
||||||
|
val tabsFragment = currentFragment as TabsFragment
|
||||||
|
tabsFragment.selectUpdates()
|
||||||
|
backHandler()
|
||||||
|
}
|
||||||
|
|
||||||
|
ACTION_INSTALL -> {
|
||||||
|
val packageName = intent.getInstallPackageName
|
||||||
|
if (!packageName.isNullOrEmpty()) {
|
||||||
|
navigateProduct(packageName)
|
||||||
|
val cacheFile = intent.getStringExtra(EXTRA_CACHE_FILE_NAME) ?: return
|
||||||
|
val installItem = packageName installFrom cacheFile
|
||||||
|
lifecycleScope.launch { installer install installItem }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Intent.ACTION_VIEW -> {
|
||||||
|
when (val deeplink = intent.deeplinkType) {
|
||||||
|
is DeeplinkType.AppDetail -> {
|
||||||
|
val fragment = currentFragment
|
||||||
|
if (fragment !is AppDetailFragment) {
|
||||||
|
navigateProduct(deeplink.packageName, deeplink.repoAddress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is DeeplinkType.AddRepository -> {
|
||||||
|
navigateAddRepository(repoAddress = deeplink.address)
|
||||||
|
}
|
||||||
|
|
||||||
|
null -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Intent.ACTION_SHOW_APP_INFO -> {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||||
|
val packageName = intent.getStringExtra(Intent.EXTRA_PACKAGE_NAME)
|
||||||
|
|
||||||
|
if (packageName != null && currentFragment !is AppDetailFragment) {
|
||||||
|
navigateProduct(packageName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun navigateFavourites() = pushFragment(FavouritesFragment())
|
||||||
|
fun navigateProduct(packageName: String, repoAddress: String? = null) =
|
||||||
|
pushFragment(AppDetailFragment(packageName, repoAddress))
|
||||||
|
|
||||||
|
fun navigateRepositories() = pushFragment(RepositoriesFragment())
|
||||||
|
fun navigatePreferences() = pushFragment(SettingsFragment.newInstance())
|
||||||
|
fun navigateAddRepository(repoAddress: String? = null) =
|
||||||
|
pushFragment(EditRepositoryFragment(null, repoAddress))
|
||||||
|
|
||||||
|
fun navigateRepository(repositoryId: Long) =
|
||||||
|
pushFragment(RepositoryFragment(repositoryId))
|
||||||
|
|
||||||
|
fun navigateEditRepository(repositoryId: Long) =
|
||||||
|
pushFragment(EditRepositoryFragment(repositoryId, null))
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.looker.droidify.content
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import com.looker.droidify.utility.common.extension.Json
|
||||||
|
import com.looker.droidify.utility.common.extension.parseDictionary
|
||||||
|
import com.looker.droidify.utility.common.extension.writeDictionary
|
||||||
|
import com.looker.droidify.model.ProductPreference
|
||||||
|
import com.looker.droidify.database.Database
|
||||||
|
import com.looker.droidify.utility.serialization.productPreference
|
||||||
|
import com.looker.droidify.utility.serialization.serialize
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.nio.charset.Charset
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
object ProductPreferences {
|
||||||
|
private val defaultProductPreference = ProductPreference(false, 0L)
|
||||||
|
private lateinit var preferences: SharedPreferences
|
||||||
|
private val mutableSubject = MutableSharedFlow<Pair<String, Long?>>()
|
||||||
|
private val subject = mutableSubject.asSharedFlow()
|
||||||
|
|
||||||
|
fun init(context: Context, scope: CoroutineScope) {
|
||||||
|
preferences = context.getSharedPreferences("product_preferences", Context.MODE_PRIVATE)
|
||||||
|
Database.LockAdapter.putAll(
|
||||||
|
preferences.all.keys.mapNotNull { packageName ->
|
||||||
|
this[packageName].databaseVersionCode?.let { Pair(packageName, it) }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
scope.launch {
|
||||||
|
subject.collect { (packageName, versionCode) ->
|
||||||
|
if (versionCode != null) {
|
||||||
|
Database.LockAdapter.put(Pair(packageName, versionCode))
|
||||||
|
} else {
|
||||||
|
Database.LockAdapter.delete(packageName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val ProductPreference.databaseVersionCode: Long?
|
||||||
|
get() = when {
|
||||||
|
ignoreUpdates -> 0L
|
||||||
|
ignoreVersionCode > 0L -> ignoreVersionCode
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun get(packageName: String): ProductPreference {
|
||||||
|
return if (preferences.contains(packageName)) {
|
||||||
|
try {
|
||||||
|
Json.factory.createParser(preferences.getString(packageName, "{}"))
|
||||||
|
.use { it.parseDictionary { productPreference() } }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
defaultProductPreference
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
defaultProductPreference
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun set(packageName: String, productPreference: ProductPreference) {
|
||||||
|
val oldProductPreference = this[packageName]
|
||||||
|
preferences.edit().putString(
|
||||||
|
packageName,
|
||||||
|
ByteArrayOutputStream().apply {
|
||||||
|
Json.factory.createGenerator(this)
|
||||||
|
.use { it.writeDictionary(productPreference::serialize) }
|
||||||
|
}.toByteArray().toString(Charset.defaultCharset())
|
||||||
|
).apply()
|
||||||
|
if (oldProductPreference.ignoreUpdates != productPreference.ignoreUpdates ||
|
||||||
|
oldProductPreference.ignoreVersionCode != productPreference.ignoreVersionCode
|
||||||
|
) {
|
||||||
|
mutableSubject.tryEmit(Pair(packageName, productPreference.databaseVersionCode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
145
app/src/main/kotlin/com/looker/droidify/database/CursorOwner.kt
Normal file
145
app/src/main/kotlin/com/looker/droidify/database/CursorOwner.kt
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.fragment.app.Fragment
|
||||||
|
import androidx.loader.app.LoaderManager
|
||||||
|
import androidx.loader.content.Loader
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.model.ProductItem
|
||||||
|
|
||||||
|
class CursorOwner : Fragment(), LoaderManager.LoaderCallbacks<Cursor> {
|
||||||
|
sealed class Request {
|
||||||
|
internal abstract val id: Int
|
||||||
|
|
||||||
|
class Available(
|
||||||
|
val searchQuery: String,
|
||||||
|
val section: ProductItem.Section,
|
||||||
|
val order: SortOrder,
|
||||||
|
) : Request() {
|
||||||
|
override val id: Int
|
||||||
|
get() = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
class Installed(
|
||||||
|
val searchQuery: String,
|
||||||
|
val section: ProductItem.Section,
|
||||||
|
val order: SortOrder,
|
||||||
|
) : Request() {
|
||||||
|
override val id: Int
|
||||||
|
get() = 2
|
||||||
|
}
|
||||||
|
|
||||||
|
class Updates(
|
||||||
|
val searchQuery: String,
|
||||||
|
val section: ProductItem.Section,
|
||||||
|
val order: SortOrder,
|
||||||
|
val skipSignatureCheck: Boolean,
|
||||||
|
) : Request() {
|
||||||
|
override val id: Int
|
||||||
|
get() = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
object Repositories : Request() {
|
||||||
|
override val id: Int
|
||||||
|
get() = 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Callback {
|
||||||
|
fun onCursorData(request: Request, cursor: Cursor?)
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class ActiveRequest(
|
||||||
|
val request: Request,
|
||||||
|
val callback: Callback?,
|
||||||
|
val cursor: Cursor?,
|
||||||
|
)
|
||||||
|
|
||||||
|
init {
|
||||||
|
retainInstance = true
|
||||||
|
}
|
||||||
|
|
||||||
|
private val activeRequests = mutableMapOf<Int, ActiveRequest>()
|
||||||
|
|
||||||
|
fun attach(callback: Callback, request: Request) {
|
||||||
|
val oldActiveRequest = activeRequests[request.id]
|
||||||
|
if (oldActiveRequest?.callback != null &&
|
||||||
|
oldActiveRequest.callback != callback && oldActiveRequest.cursor != null
|
||||||
|
) {
|
||||||
|
oldActiveRequest.callback.onCursorData(oldActiveRequest.request, null)
|
||||||
|
}
|
||||||
|
val cursor = if (oldActiveRequest?.request == request && oldActiveRequest.cursor != null) {
|
||||||
|
callback.onCursorData(request, oldActiveRequest.cursor)
|
||||||
|
oldActiveRequest.cursor
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
activeRequests[request.id] = ActiveRequest(request, callback, cursor)
|
||||||
|
if (cursor == null) {
|
||||||
|
LoaderManager.getInstance(this).restartLoader(request.id, null, this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun detach(callback: Callback) {
|
||||||
|
for (id in activeRequests.keys) {
|
||||||
|
val activeRequest = activeRequests[id]!!
|
||||||
|
if (activeRequest.callback == callback) {
|
||||||
|
activeRequests[id] = activeRequest.copy(callback = null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
|
||||||
|
val request = activeRequests[id]!!.request
|
||||||
|
return QueryLoader(requireContext()) {
|
||||||
|
when (request) {
|
||||||
|
is Request.Available ->
|
||||||
|
Database.ProductAdapter
|
||||||
|
.query(
|
||||||
|
installed = false,
|
||||||
|
updates = false,
|
||||||
|
searchQuery = request.searchQuery,
|
||||||
|
section = request.section,
|
||||||
|
order = request.order,
|
||||||
|
signal = it,
|
||||||
|
)
|
||||||
|
|
||||||
|
is Request.Installed ->
|
||||||
|
Database.ProductAdapter
|
||||||
|
.query(
|
||||||
|
installed = true,
|
||||||
|
updates = false,
|
||||||
|
searchQuery = request.searchQuery,
|
||||||
|
section = request.section,
|
||||||
|
order = request.order,
|
||||||
|
signal = it,
|
||||||
|
)
|
||||||
|
|
||||||
|
is Request.Updates ->
|
||||||
|
Database.ProductAdapter
|
||||||
|
.query(
|
||||||
|
installed = true,
|
||||||
|
updates = true,
|
||||||
|
searchQuery = request.searchQuery,
|
||||||
|
section = request.section,
|
||||||
|
order = request.order,
|
||||||
|
signal = it,
|
||||||
|
skipSignatureCheck = request.skipSignatureCheck,
|
||||||
|
)
|
||||||
|
|
||||||
|
is Request.Repositories -> Database.RepositoryAdapter.query(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
|
||||||
|
val activeRequest = activeRequests[loader.id]
|
||||||
|
if (activeRequest != null) {
|
||||||
|
activeRequests[loader.id] = activeRequest.copy(cursor = data)
|
||||||
|
activeRequest.callback?.onCursorData(activeRequest.request, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onLoaderReset(loader: Loader<Cursor>) = onLoadFinished(loader, null)
|
||||||
|
}
|
||||||
982
app/src/main/kotlin/com/looker/droidify/database/Database.kt
Normal file
982
app/src/main/kotlin/com/looker/droidify/database/Database.kt
Normal file
@@ -0,0 +1,982 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.database.sqlite.SQLiteDatabase
|
||||||
|
import android.database.sqlite.SQLiteOpenHelper
|
||||||
|
import android.os.CancellationSignal
|
||||||
|
import androidx.core.database.sqlite.transaction
|
||||||
|
import com.fasterxml.jackson.core.JsonGenerator
|
||||||
|
import com.fasterxml.jackson.core.JsonParser
|
||||||
|
import com.looker.droidify.BuildConfig
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.model.InstalledItem
|
||||||
|
import com.looker.droidify.model.Product
|
||||||
|
import com.looker.droidify.model.ProductItem
|
||||||
|
import com.looker.droidify.model.Repository
|
||||||
|
import com.looker.droidify.utility.common.extension.Json
|
||||||
|
import com.looker.droidify.utility.common.extension.asSequence
|
||||||
|
import com.looker.droidify.utility.common.extension.firstOrNull
|
||||||
|
import com.looker.droidify.utility.common.extension.parseDictionary
|
||||||
|
import com.looker.droidify.utility.common.extension.writeDictionary
|
||||||
|
import com.looker.droidify.utility.common.log
|
||||||
|
import com.looker.droidify.utility.serialization.product
|
||||||
|
import com.looker.droidify.utility.serialization.productItem
|
||||||
|
import com.looker.droidify.utility.serialization.repository
|
||||||
|
import com.looker.droidify.utility.serialization.serialize
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.emitAll
|
||||||
|
import kotlinx.coroutines.flow.flowOf
|
||||||
|
import kotlinx.coroutines.flow.flowOn
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.onCompletion
|
||||||
|
import kotlinx.coroutines.flow.onEach
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import kotlin.collections.component1
|
||||||
|
import kotlin.collections.component2
|
||||||
|
import kotlin.collections.set
|
||||||
|
|
||||||
|
object Database {
|
||||||
|
fun init(context: Context): Boolean {
|
||||||
|
val helper = Helper(context)
|
||||||
|
db = helper.writableDatabase
|
||||||
|
if (helper.created) {
|
||||||
|
for (repository in Repository.defaultRepositories.sortedBy { it.name }) {
|
||||||
|
RepositoryAdapter.put(repository)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RepositoryAdapter.removeDuplicates()
|
||||||
|
return helper.created || helper.updated
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var db: SQLiteDatabase
|
||||||
|
|
||||||
|
private interface Table {
|
||||||
|
val memory: Boolean
|
||||||
|
val innerName: String
|
||||||
|
val createTable: String
|
||||||
|
val createIndex: String?
|
||||||
|
get() = null
|
||||||
|
|
||||||
|
val databasePrefix: String
|
||||||
|
get() = if (memory) "memory." else ""
|
||||||
|
|
||||||
|
val name: String
|
||||||
|
get() = "$databasePrefix$innerName"
|
||||||
|
|
||||||
|
fun formatCreateTable(name: String): String {
|
||||||
|
return buildString(128) {
|
||||||
|
append("CREATE TABLE ")
|
||||||
|
append(name)
|
||||||
|
append(" (")
|
||||||
|
trimAndJoin(createTable)
|
||||||
|
append(")")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val createIndexPairFormatted: Pair<String, String>?
|
||||||
|
get() = createIndex?.let {
|
||||||
|
Pair(
|
||||||
|
"CREATE INDEX ${innerName}_index ON $innerName ($it)",
|
||||||
|
"CREATE INDEX ${name}_index ON $innerName ($it)",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private object Schema {
|
||||||
|
object Repository : Table {
|
||||||
|
const val ROW_ID = "_id"
|
||||||
|
const val ROW_ENABLED = "enabled"
|
||||||
|
const val ROW_DELETED = "deleted"
|
||||||
|
const val ROW_DATA = "data"
|
||||||
|
|
||||||
|
override val memory = false
|
||||||
|
override val innerName = "repository"
|
||||||
|
override val createTable = """
|
||||||
|
$ROW_ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
$ROW_ENABLED INTEGER NOT NULL,
|
||||||
|
$ROW_DELETED INTEGER NOT NULL,
|
||||||
|
$ROW_DATA BLOB NOT NULL
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
object Product : Table {
|
||||||
|
const val ROW_REPOSITORY_ID = "repository_id"
|
||||||
|
const val ROW_PACKAGE_NAME = "package_name"
|
||||||
|
const val ROW_NAME = "name"
|
||||||
|
const val ROW_SUMMARY = "summary"
|
||||||
|
const val ROW_DESCRIPTION = "description"
|
||||||
|
const val ROW_ADDED = "added"
|
||||||
|
const val ROW_UPDATED = "updated"
|
||||||
|
const val ROW_VERSION_CODE = "version_code"
|
||||||
|
const val ROW_SIGNATURES = "signatures"
|
||||||
|
const val ROW_COMPATIBLE = "compatible"
|
||||||
|
const val ROW_DATA = "data"
|
||||||
|
const val ROW_DATA_ITEM = "data_item"
|
||||||
|
|
||||||
|
override val memory = false
|
||||||
|
override val innerName = "product"
|
||||||
|
override val createTable = """
|
||||||
|
$ROW_REPOSITORY_ID INTEGER NOT NULL,
|
||||||
|
$ROW_PACKAGE_NAME TEXT NOT NULL,
|
||||||
|
$ROW_NAME TEXT NOT NULL,
|
||||||
|
$ROW_SUMMARY TEXT NOT NULL,
|
||||||
|
$ROW_DESCRIPTION TEXT NOT NULL,
|
||||||
|
$ROW_ADDED INTEGER NOT NULL,
|
||||||
|
$ROW_UPDATED INTEGER NOT NULL,
|
||||||
|
$ROW_VERSION_CODE INTEGER NOT NULL,
|
||||||
|
$ROW_SIGNATURES TEXT NOT NULL,
|
||||||
|
$ROW_COMPATIBLE INTEGER NOT NULL,
|
||||||
|
$ROW_DATA BLOB NOT NULL,
|
||||||
|
$ROW_DATA_ITEM BLOB NOT NULL,
|
||||||
|
PRIMARY KEY ($ROW_REPOSITORY_ID, $ROW_PACKAGE_NAME)
|
||||||
|
"""
|
||||||
|
override val createIndex = ROW_PACKAGE_NAME
|
||||||
|
}
|
||||||
|
|
||||||
|
object Category : Table {
|
||||||
|
const val ROW_REPOSITORY_ID = "repository_id"
|
||||||
|
const val ROW_PACKAGE_NAME = "package_name"
|
||||||
|
const val ROW_NAME = "name"
|
||||||
|
|
||||||
|
override val memory = false
|
||||||
|
override val innerName = "category"
|
||||||
|
override val createTable = """
|
||||||
|
$ROW_REPOSITORY_ID INTEGER NOT NULL,
|
||||||
|
$ROW_PACKAGE_NAME TEXT NOT NULL,
|
||||||
|
$ROW_NAME TEXT NOT NULL,
|
||||||
|
PRIMARY KEY ($ROW_REPOSITORY_ID, $ROW_PACKAGE_NAME, $ROW_NAME)
|
||||||
|
"""
|
||||||
|
override val createIndex = "$ROW_PACKAGE_NAME, $ROW_NAME"
|
||||||
|
}
|
||||||
|
|
||||||
|
object Installed : Table {
|
||||||
|
const val ROW_PACKAGE_NAME = "package_name"
|
||||||
|
const val ROW_VERSION = "version"
|
||||||
|
const val ROW_VERSION_CODE = "version_code"
|
||||||
|
const val ROW_SIGNATURE = "signature"
|
||||||
|
|
||||||
|
override val memory = true
|
||||||
|
override val innerName = "installed"
|
||||||
|
override val createTable = """
|
||||||
|
$ROW_PACKAGE_NAME TEXT PRIMARY KEY,
|
||||||
|
$ROW_VERSION TEXT NOT NULL,
|
||||||
|
$ROW_VERSION_CODE INTEGER NOT NULL,
|
||||||
|
$ROW_SIGNATURE TEXT NOT NULL
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
object Lock : Table {
|
||||||
|
const val ROW_PACKAGE_NAME = "package_name"
|
||||||
|
const val ROW_VERSION_CODE = "version_code"
|
||||||
|
|
||||||
|
override val memory = true
|
||||||
|
override val innerName = "lock"
|
||||||
|
override val createTable = """
|
||||||
|
$ROW_PACKAGE_NAME TEXT PRIMARY KEY,
|
||||||
|
$ROW_VERSION_CODE INTEGER NOT NULL
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
|
||||||
|
object Synthetic {
|
||||||
|
const val ROW_CAN_UPDATE = "can_update"
|
||||||
|
const val ROW_MATCH_RANK = "match_rank"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Helper(context: Context) : SQLiteOpenHelper(context, "droidify", null, 5) {
|
||||||
|
var created = false
|
||||||
|
private set
|
||||||
|
var updated = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
override fun onCreate(db: SQLiteDatabase) = Unit
|
||||||
|
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) =
|
||||||
|
onVersionChange(db)
|
||||||
|
|
||||||
|
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) =
|
||||||
|
onVersionChange(db)
|
||||||
|
|
||||||
|
private fun onVersionChange(db: SQLiteDatabase) {
|
||||||
|
handleTables(db, true, Schema.Product, Schema.Category)
|
||||||
|
addRepos(db, Repository.newlyAdded)
|
||||||
|
this.updated = true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onOpen(db: SQLiteDatabase) {
|
||||||
|
val create = handleTables(db, false, Schema.Repository)
|
||||||
|
val updated = handleTables(db, create, Schema.Product, Schema.Category)
|
||||||
|
db.execSQL("ATTACH DATABASE ':memory:' AS memory")
|
||||||
|
handleTables(db, false, Schema.Installed, Schema.Lock)
|
||||||
|
handleIndexes(
|
||||||
|
db,
|
||||||
|
Schema.Repository,
|
||||||
|
Schema.Product,
|
||||||
|
Schema.Category,
|
||||||
|
Schema.Installed,
|
||||||
|
Schema.Lock,
|
||||||
|
)
|
||||||
|
dropOldTables(db, Schema.Repository, Schema.Product, Schema.Category)
|
||||||
|
this.created = this.created || create
|
||||||
|
this.updated = this.updated || create || updated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleTables(db: SQLiteDatabase, recreate: Boolean, vararg tables: Table): Boolean {
|
||||||
|
val shouldRecreate = recreate || tables.any { table ->
|
||||||
|
val sql = db.query(
|
||||||
|
"${table.databasePrefix}sqlite_master",
|
||||||
|
columns = arrayOf("sql"),
|
||||||
|
selection = Pair("type = ? AND name = ?", arrayOf("table", table.innerName)),
|
||||||
|
).use { it.firstOrNull()?.getString(0) }.orEmpty()
|
||||||
|
table.formatCreateTable(table.innerName) != sql
|
||||||
|
}
|
||||||
|
return shouldRecreate && run {
|
||||||
|
val shouldVacuum = tables.map {
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${it.name}")
|
||||||
|
db.execSQL(it.formatCreateTable(it.name))
|
||||||
|
!it.memory
|
||||||
|
}
|
||||||
|
if (shouldVacuum.any { it } && !db.inTransaction()) {
|
||||||
|
db.execSQL("VACUUM")
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addRepos(db: SQLiteDatabase, repos: List<Repository>) {
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
log("Add Repos: $repos", "RepositoryAdapter")
|
||||||
|
}
|
||||||
|
if (repos.isEmpty()) return
|
||||||
|
db.transaction {
|
||||||
|
repos.forEach {
|
||||||
|
RepositoryAdapter.put(it, database = this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleIndexes(db: SQLiteDatabase, vararg tables: Table) {
|
||||||
|
val shouldVacuum = tables.map { table ->
|
||||||
|
val sqls = db.query(
|
||||||
|
"${table.databasePrefix}sqlite_master",
|
||||||
|
columns = arrayOf("name", "sql"),
|
||||||
|
selection = Pair("type = ? AND tbl_name = ?", arrayOf("index", table.innerName)),
|
||||||
|
)
|
||||||
|
.use { cursor ->
|
||||||
|
cursor.asSequence()
|
||||||
|
.mapNotNull { it.getString(1)?.let { sql -> Pair(it.getString(0), sql) } }
|
||||||
|
.toList()
|
||||||
|
}
|
||||||
|
.filter { !it.first.startsWith("sqlite_") }
|
||||||
|
val createIndexes = table.createIndexPairFormatted?.let { listOf(it) }.orEmpty()
|
||||||
|
createIndexes.map { it.first } != sqls.map { it.second } && run {
|
||||||
|
for (name in sqls.map { it.first }) {
|
||||||
|
db.execSQL("DROP INDEX IF EXISTS $name")
|
||||||
|
}
|
||||||
|
for (createIndexPair in createIndexes) {
|
||||||
|
db.execSQL(createIndexPair.second)
|
||||||
|
}
|
||||||
|
!table.memory
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shouldVacuum.any { it } && !db.inTransaction()) {
|
||||||
|
db.execSQL("VACUUM")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dropOldTables(db: SQLiteDatabase, vararg neededTables: Table) {
|
||||||
|
val tables = db.query(
|
||||||
|
"sqlite_master",
|
||||||
|
columns = arrayOf("name"),
|
||||||
|
selection = Pair("type = ?", arrayOf("table")),
|
||||||
|
)
|
||||||
|
.use { cursor -> cursor.asSequence().mapNotNull { it.getString(0) }.toList() }
|
||||||
|
.filter { !it.startsWith("sqlite_") && !it.startsWith("android_") }
|
||||||
|
.toSet() - neededTables.mapNotNull { if (it.memory) null else it.name }.toSet()
|
||||||
|
if (tables.isNotEmpty()) {
|
||||||
|
for (table in tables) {
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS $table")
|
||||||
|
}
|
||||||
|
if (!db.inTransaction()) {
|
||||||
|
db.execSQL("VACUUM")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class Subject {
|
||||||
|
data object Repositories : Subject()
|
||||||
|
data class Repository(val id: Long) : Subject()
|
||||||
|
data object Products : Subject()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val observers = mutableMapOf<Subject, MutableSet<() -> Unit>>()
|
||||||
|
|
||||||
|
private fun dataObservable(subject: Subject): (Boolean, () -> Unit) -> Unit =
|
||||||
|
{ register, observer ->
|
||||||
|
synchronized(observers) {
|
||||||
|
val set = observers[subject] ?: run {
|
||||||
|
val set = mutableSetOf<() -> Unit>()
|
||||||
|
observers[subject] = set
|
||||||
|
set
|
||||||
|
}
|
||||||
|
if (register) {
|
||||||
|
set += observer
|
||||||
|
} else {
|
||||||
|
set -= observer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun flowCollection(subject: Subject): Flow<Unit> = callbackFlow {
|
||||||
|
val callback: () -> Unit = { trySend(Unit) }
|
||||||
|
val dataObservable = dataObservable(subject)
|
||||||
|
dataObservable(true, callback)
|
||||||
|
|
||||||
|
awaitClose { dataObservable(false, callback) }
|
||||||
|
}.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
private fun notifyChanged(vararg subjects: Subject) {
|
||||||
|
synchronized(observers) {
|
||||||
|
subjects.asSequence().mapNotNull { observers[it] }.flatten().forEach { it() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun SQLiteDatabase.insertOrReplace(
|
||||||
|
replace: Boolean,
|
||||||
|
table: String,
|
||||||
|
contentValues: ContentValues,
|
||||||
|
): Long {
|
||||||
|
return if (replace) {
|
||||||
|
replace(table, null, contentValues)
|
||||||
|
} else {
|
||||||
|
insert(
|
||||||
|
table,
|
||||||
|
null,
|
||||||
|
contentValues,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun SQLiteDatabase.query(
|
||||||
|
table: String,
|
||||||
|
columns: Array<String>? = null,
|
||||||
|
selection: Pair<String, Array<String>>? = null,
|
||||||
|
orderBy: String? = null,
|
||||||
|
signal: CancellationSignal? = null,
|
||||||
|
): Cursor {
|
||||||
|
return query(
|
||||||
|
false,
|
||||||
|
table,
|
||||||
|
columns,
|
||||||
|
selection?.first,
|
||||||
|
selection?.second,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
orderBy,
|
||||||
|
null,
|
||||||
|
signal,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Cursor.observable(subject: Subject): ObservableCursor {
|
||||||
|
return ObservableCursor(this, dataObservable(subject))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> ByteArray.jsonParse(callback: (JsonParser) -> T): T {
|
||||||
|
return Json.factory.createParser(this).use { it.parseDictionary(callback) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun jsonGenerate(callback: (JsonGenerator) -> Unit): ByteArray {
|
||||||
|
val outputStream = ByteArrayOutputStream()
|
||||||
|
Json.factory.createGenerator(outputStream).use { it.writeDictionary(callback) }
|
||||||
|
return outputStream.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
object RepositoryAdapter {
|
||||||
|
internal fun putWithoutNotification(
|
||||||
|
repository: Repository,
|
||||||
|
shouldReplace: Boolean,
|
||||||
|
database: SQLiteDatabase,
|
||||||
|
): Long {
|
||||||
|
return database.insertOrReplace(
|
||||||
|
shouldReplace,
|
||||||
|
Schema.Repository.name,
|
||||||
|
ContentValues().apply {
|
||||||
|
if (shouldReplace) {
|
||||||
|
put(Schema.Repository.ROW_ID, repository.id)
|
||||||
|
}
|
||||||
|
put(Schema.Repository.ROW_ENABLED, if (repository.enabled) 1 else 0)
|
||||||
|
put(Schema.Repository.ROW_DELETED, 0)
|
||||||
|
put(Schema.Repository.ROW_DATA, jsonGenerate(repository::serialize))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun put(repository: Repository, database: SQLiteDatabase = db): Repository {
|
||||||
|
val shouldReplace = repository.id >= 0L
|
||||||
|
val newId = putWithoutNotification(repository, shouldReplace, database)
|
||||||
|
val id = if (shouldReplace) repository.id else newId
|
||||||
|
notifyChanged(Subject.Repositories, Subject.Repository(id), Subject.Products)
|
||||||
|
return if (newId != repository.id) repository.copy(id = newId) else repository
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeDuplicates() {
|
||||||
|
db.transaction {
|
||||||
|
val all = getAll()
|
||||||
|
val different = all.distinctBy { it.address }
|
||||||
|
val duplicates = all - different.toSet()
|
||||||
|
duplicates.forEach {
|
||||||
|
markAsDeleted(it.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getStream(id: Long): Flow<Repository?> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Repositories)) }
|
||||||
|
.map { get(id) }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
fun get(id: Long): Repository? {
|
||||||
|
return db.query(
|
||||||
|
Schema.Repository.name,
|
||||||
|
selection = Pair(
|
||||||
|
"${Schema.Repository.ROW_ID} = ? AND ${Schema.Repository.ROW_DELETED} == 0",
|
||||||
|
arrayOf(id.toString()),
|
||||||
|
),
|
||||||
|
).use { it.firstOrNull()?.let(::transform) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAllStream(): Flow<List<Repository>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Repositories)) }
|
||||||
|
.map { getAll() }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
fun getEnabledStream(): Flow<List<Repository>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Repositories)) }
|
||||||
|
.map { getEnabled() }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
private suspend fun getEnabled(): List<Repository> = withContext(Dispatchers.IO) {
|
||||||
|
db.query(
|
||||||
|
Schema.Repository.name,
|
||||||
|
selection = Pair(
|
||||||
|
"${Schema.Repository.ROW_ENABLED} != 0 AND " +
|
||||||
|
"${Schema.Repository.ROW_DELETED} == 0",
|
||||||
|
emptyArray(),
|
||||||
|
),
|
||||||
|
signal = null,
|
||||||
|
).use { it.asSequence().map(::transform).toList() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAll(): List<Repository> {
|
||||||
|
return db.query(
|
||||||
|
Schema.Repository.name,
|
||||||
|
selection = Pair("${Schema.Repository.ROW_DELETED} == 0", emptyArray()),
|
||||||
|
signal = null,
|
||||||
|
).use { it.asSequence().map(::transform).toList() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAllRemovedStream(): Flow<Map<Long, Boolean>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Repositories)) }
|
||||||
|
.map { getAllDisabledDeleted() }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
private fun getAllDisabledDeleted(): Map<Long, Boolean> {
|
||||||
|
return db.query(
|
||||||
|
Schema.Repository.name,
|
||||||
|
columns = arrayOf(Schema.Repository.ROW_ID, Schema.Repository.ROW_DELETED),
|
||||||
|
selection = Pair(
|
||||||
|
"${Schema.Repository.ROW_ENABLED} == 0 OR " +
|
||||||
|
"${Schema.Repository.ROW_DELETED} != 0",
|
||||||
|
emptyArray(),
|
||||||
|
),
|
||||||
|
signal = null,
|
||||||
|
).use { parentCursor ->
|
||||||
|
parentCursor.asSequence().associate {
|
||||||
|
val idIndex = it.getColumnIndexOrThrow(Schema.Repository.ROW_ID)
|
||||||
|
val isDeletedIndex = it.getColumnIndexOrThrow(Schema.Repository.ROW_DELETED)
|
||||||
|
it.getLong(idIndex) to (it.getInt(isDeletedIndex) != 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun markAsDeleted(id: Long) {
|
||||||
|
db.update(
|
||||||
|
Schema.Repository.name,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(Schema.Repository.ROW_DELETED, 1)
|
||||||
|
},
|
||||||
|
"${Schema.Repository.ROW_ID} = ?",
|
||||||
|
arrayOf(id.toString()),
|
||||||
|
)
|
||||||
|
notifyChanged(Subject.Repositories, Subject.Repository(id), Subject.Products)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cleanup(removedRepos: Map<Long, Boolean>) {
|
||||||
|
val result = removedRepos.map { (id, isDeleted) ->
|
||||||
|
val idsString = id.toString()
|
||||||
|
val productsCount = db.delete(
|
||||||
|
Schema.Product.name,
|
||||||
|
"${Schema.Product.ROW_REPOSITORY_ID} IN ($idsString)",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
val categoriesCount = db.delete(
|
||||||
|
Schema.Category.name,
|
||||||
|
"${Schema.Category.ROW_REPOSITORY_ID} IN ($idsString)",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
if (isDeleted) {
|
||||||
|
db.delete(
|
||||||
|
Schema.Repository.name,
|
||||||
|
"${Schema.Repository.ROW_ID} IN ($id)",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
productsCount != 0 || categoriesCount != 0
|
||||||
|
}
|
||||||
|
if (result.any { it }) {
|
||||||
|
notifyChanged(Subject.Products)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun importRepos(list: List<Repository>) {
|
||||||
|
db.transaction {
|
||||||
|
val currentAddresses = getAll().map { it.address }
|
||||||
|
val newRepos = list
|
||||||
|
.filter { it.address !in currentAddresses }
|
||||||
|
newRepos.forEach { put(it) }
|
||||||
|
removeDuplicates()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun query(signal: CancellationSignal?): Cursor {
|
||||||
|
return db.query(
|
||||||
|
Schema.Repository.name,
|
||||||
|
selection = Pair("${Schema.Repository.ROW_DELETED} == 0", emptyArray()),
|
||||||
|
orderBy = "${Schema.Repository.ROW_ENABLED} DESC",
|
||||||
|
signal = signal,
|
||||||
|
).observable(Subject.Repositories)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun transform(cursor: Cursor): Repository {
|
||||||
|
return cursor.getBlob(cursor.getColumnIndexOrThrow(Schema.Repository.ROW_DATA))
|
||||||
|
.jsonParse {
|
||||||
|
it.repository().apply {
|
||||||
|
this.id =
|
||||||
|
cursor.getLong(cursor.getColumnIndexOrThrow(Schema.Repository.ROW_ID))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object ProductAdapter {
|
||||||
|
|
||||||
|
fun getStream(packageName: String): Flow<List<Product>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Products)) }
|
||||||
|
.map { get(packageName, null) }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
suspend fun getUpdates(skipSignatureCheck: Boolean): List<ProductItem> =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
query(
|
||||||
|
installed = true,
|
||||||
|
updates = true,
|
||||||
|
searchQuery = "",
|
||||||
|
skipSignatureCheck = skipSignatureCheck,
|
||||||
|
section = ProductItem.Section.All,
|
||||||
|
order = SortOrder.NAME,
|
||||||
|
signal = null,
|
||||||
|
).use {
|
||||||
|
it.asSequence()
|
||||||
|
.map(ProductAdapter::transformItem)
|
||||||
|
.toList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getUpdatesStream(skipSignatureCheck: Boolean): Flow<List<ProductItem>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Products)) }
|
||||||
|
// Crashes due to immediate retrieval of data?
|
||||||
|
.onEach { delay(50) }
|
||||||
|
.map { getUpdates(skipSignatureCheck) }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
fun get(packageName: String, signal: CancellationSignal?): List<Product> {
|
||||||
|
return db.query(
|
||||||
|
Schema.Product.name,
|
||||||
|
columns = arrayOf(
|
||||||
|
Schema.Product.ROW_REPOSITORY_ID,
|
||||||
|
Schema.Product.ROW_DESCRIPTION,
|
||||||
|
Schema.Product.ROW_DATA,
|
||||||
|
),
|
||||||
|
selection = Pair("${Schema.Product.ROW_PACKAGE_NAME} = ?", arrayOf(packageName)),
|
||||||
|
signal = signal,
|
||||||
|
).use { it.asSequence().map(::transform).toList() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getCountStream(repositoryId: Long): Flow<Int> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Products)) }
|
||||||
|
.map { getCount(repositoryId) }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
private fun getCount(repositoryId: Long): Int {
|
||||||
|
return db.query(
|
||||||
|
Schema.Product.name,
|
||||||
|
columns = arrayOf("COUNT (*)"),
|
||||||
|
selection = Pair(
|
||||||
|
"${Schema.Product.ROW_REPOSITORY_ID} = ?",
|
||||||
|
arrayOf(repositoryId.toString()),
|
||||||
|
),
|
||||||
|
).use { it.firstOrNull()?.getInt(0) ?: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun query(
|
||||||
|
installed: Boolean,
|
||||||
|
updates: Boolean,
|
||||||
|
skipSignatureCheck: Boolean = false,
|
||||||
|
searchQuery: String,
|
||||||
|
section: ProductItem.Section,
|
||||||
|
order: SortOrder,
|
||||||
|
signal: CancellationSignal?,
|
||||||
|
): Cursor {
|
||||||
|
val builder = QueryBuilder()
|
||||||
|
|
||||||
|
val signatureMatches = if (skipSignatureCheck) "1"
|
||||||
|
else """installed.${Schema.Installed.ROW_SIGNATURE} IS NOT NULL AND
|
||||||
|
product.${Schema.Product.ROW_SIGNATURES} LIKE ('%.' || installed.${Schema.Installed.ROW_SIGNATURE} || '.%') AND
|
||||||
|
product.${Schema.Product.ROW_SIGNATURES} != ''"""
|
||||||
|
|
||||||
|
builder += """SELECT product.rowid AS _id, product.${Schema.Product.ROW_REPOSITORY_ID},
|
||||||
|
product.${Schema.Product.ROW_PACKAGE_NAME}, product.${Schema.Product.ROW_NAME},
|
||||||
|
product.${Schema.Product.ROW_SUMMARY}, installed.${Schema.Installed.ROW_VERSION},
|
||||||
|
(COALESCE(lock.${Schema.Lock.ROW_VERSION_CODE}, -1) NOT IN (0, product.${Schema.Product.ROW_VERSION_CODE}) AND
|
||||||
|
product.${Schema.Product.ROW_COMPATIBLE} != 0 AND product.${Schema.Product.ROW_VERSION_CODE} >
|
||||||
|
COALESCE(installed.${Schema.Installed.ROW_VERSION_CODE}, 0xffffffff) AND $signatureMatches)
|
||||||
|
AS ${Schema.Synthetic.ROW_CAN_UPDATE}, product.${Schema.Product.ROW_COMPATIBLE},
|
||||||
|
product.${Schema.Product.ROW_DATA_ITEM},"""
|
||||||
|
|
||||||
|
if (searchQuery.isNotEmpty()) {
|
||||||
|
builder += """(((product.${Schema.Product.ROW_NAME} LIKE ? OR
|
||||||
|
product.${Schema.Product.ROW_SUMMARY} LIKE ?) * 7) |
|
||||||
|
((product.${Schema.Product.ROW_PACKAGE_NAME} LIKE ?) * 3) |
|
||||||
|
(product.${Schema.Product.ROW_DESCRIPTION} LIKE ?)) AS ${Schema.Synthetic.ROW_MATCH_RANK},"""
|
||||||
|
builder %= List(4) { "%$searchQuery%" }
|
||||||
|
} else {
|
||||||
|
builder += "0 AS ${Schema.Synthetic.ROW_MATCH_RANK},"
|
||||||
|
}
|
||||||
|
|
||||||
|
builder += """MAX((product.${Schema.Product.ROW_COMPATIBLE} AND
|
||||||
|
(installed.${Schema.Installed.ROW_SIGNATURE} IS NULL OR $signatureMatches)) ||
|
||||||
|
PRINTF('%016X', product.${Schema.Product.ROW_VERSION_CODE})) FROM ${Schema.Product.name} AS product"""
|
||||||
|
builder += """JOIN ${Schema.Repository.name} AS repository
|
||||||
|
ON product.${Schema.Product.ROW_REPOSITORY_ID} = repository.${Schema.Repository.ROW_ID}"""
|
||||||
|
builder += """LEFT JOIN ${Schema.Lock.name} AS lock
|
||||||
|
ON product.${Schema.Product.ROW_PACKAGE_NAME} = lock.${Schema.Lock.ROW_PACKAGE_NAME}"""
|
||||||
|
|
||||||
|
if (!installed && !updates) {
|
||||||
|
builder += "LEFT"
|
||||||
|
}
|
||||||
|
builder += """JOIN ${Schema.Installed.name} AS installed
|
||||||
|
ON product.${Schema.Product.ROW_PACKAGE_NAME} = installed.${Schema.Installed.ROW_PACKAGE_NAME}"""
|
||||||
|
|
||||||
|
if (section is ProductItem.Section.Category) {
|
||||||
|
builder += """JOIN ${Schema.Category.name} AS category
|
||||||
|
ON product.${Schema.Product.ROW_PACKAGE_NAME} = category.${Schema.Product.ROW_PACKAGE_NAME}"""
|
||||||
|
}
|
||||||
|
|
||||||
|
builder += """WHERE repository.${Schema.Repository.ROW_ENABLED} != 0 AND
|
||||||
|
repository.${Schema.Repository.ROW_DELETED} == 0"""
|
||||||
|
|
||||||
|
if (section is ProductItem.Section.Category) {
|
||||||
|
builder += "AND category.${Schema.Category.ROW_NAME} = ?"
|
||||||
|
builder %= section.name
|
||||||
|
} else if (section is ProductItem.Section.Repository) {
|
||||||
|
builder += "AND product.${Schema.Product.ROW_REPOSITORY_ID} = ?"
|
||||||
|
builder %= section.id.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchQuery.isNotEmpty()) {
|
||||||
|
builder += """AND ${Schema.Synthetic.ROW_MATCH_RANK} > 0"""
|
||||||
|
}
|
||||||
|
|
||||||
|
builder += "GROUP BY product.${Schema.Product.ROW_PACKAGE_NAME} HAVING 1"
|
||||||
|
|
||||||
|
if (updates) {
|
||||||
|
builder += "AND ${Schema.Synthetic.ROW_CAN_UPDATE}"
|
||||||
|
}
|
||||||
|
builder += "ORDER BY"
|
||||||
|
|
||||||
|
if (searchQuery.isNotEmpty()) {
|
||||||
|
builder += """${Schema.Synthetic.ROW_MATCH_RANK} DESC,"""
|
||||||
|
}
|
||||||
|
|
||||||
|
when (order) {
|
||||||
|
SortOrder.UPDATED -> builder += "product.${Schema.Product.ROW_UPDATED} DESC,"
|
||||||
|
SortOrder.ADDED -> builder += "product.${Schema.Product.ROW_ADDED} DESC,"
|
||||||
|
SortOrder.NAME -> Unit
|
||||||
|
}::class
|
||||||
|
builder += "product.${Schema.Product.ROW_NAME} COLLATE LOCALIZED ASC"
|
||||||
|
|
||||||
|
return builder.query(db, signal).observable(Subject.Products)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun transform(cursor: Cursor): Product {
|
||||||
|
return cursor.getBlob(cursor.getColumnIndexOrThrow(Schema.Product.ROW_DATA))
|
||||||
|
.jsonParse {
|
||||||
|
it.product().apply {
|
||||||
|
this.repositoryId = cursor
|
||||||
|
.getLong(cursor.getColumnIndexOrThrow(Schema.Product.ROW_REPOSITORY_ID))
|
||||||
|
this.description = cursor
|
||||||
|
.getString(cursor.getColumnIndexOrThrow(Schema.Product.ROW_DESCRIPTION))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun transformPackageName(cursor: Cursor): String {
|
||||||
|
return cursor.getString(cursor.getColumnIndexOrThrow(Schema.Product.ROW_PACKAGE_NAME))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun transformItem(cursor: Cursor): ProductItem {
|
||||||
|
return cursor.getBlob(cursor.getColumnIndexOrThrow(Schema.Product.ROW_DATA_ITEM))
|
||||||
|
.jsonParse {
|
||||||
|
it.productItem().apply {
|
||||||
|
this.repositoryId = cursor
|
||||||
|
.getLong(cursor.getColumnIndexOrThrow(Schema.Product.ROW_REPOSITORY_ID))
|
||||||
|
this.packageName = cursor
|
||||||
|
.getString(cursor.getColumnIndexOrThrow(Schema.Product.ROW_PACKAGE_NAME))
|
||||||
|
this.name = cursor
|
||||||
|
.getString(cursor.getColumnIndexOrThrow(Schema.Product.ROW_NAME))
|
||||||
|
this.summary = cursor
|
||||||
|
.getString(cursor.getColumnIndexOrThrow(Schema.Product.ROW_SUMMARY))
|
||||||
|
this.installedVersion = cursor
|
||||||
|
.getString(cursor.getColumnIndexOrThrow(Schema.Installed.ROW_VERSION))
|
||||||
|
.orEmpty()
|
||||||
|
this.compatible = cursor
|
||||||
|
.getInt(cursor.getColumnIndexOrThrow(Schema.Product.ROW_COMPATIBLE)) != 0
|
||||||
|
this.canUpdate = cursor
|
||||||
|
.getInt(cursor.getColumnIndexOrThrow(Schema.Synthetic.ROW_CAN_UPDATE)) != 0
|
||||||
|
this.matchRank = cursor
|
||||||
|
.getInt(cursor.getColumnIndexOrThrow(Schema.Synthetic.ROW_MATCH_RANK))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object CategoryAdapter {
|
||||||
|
|
||||||
|
fun getAllStream(): Flow<Set<String>> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Products)) }
|
||||||
|
.map { getAll() }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
private suspend fun getAll(): Set<String> = withContext(Dispatchers.IO) {
|
||||||
|
val builder = QueryBuilder()
|
||||||
|
|
||||||
|
builder += """SELECT DISTINCT category.${Schema.Category.ROW_NAME}
|
||||||
|
FROM ${Schema.Category.name} AS category
|
||||||
|
JOIN ${Schema.Repository.name} AS repository
|
||||||
|
ON category.${Schema.Category.ROW_REPOSITORY_ID} = repository.${Schema.Repository.ROW_ID}
|
||||||
|
WHERE repository.${Schema.Repository.ROW_ENABLED} != 0 AND
|
||||||
|
repository.${Schema.Repository.ROW_DELETED} == 0"""
|
||||||
|
|
||||||
|
builder.query(db, null).use { cursor ->
|
||||||
|
cursor.asSequence().map {
|
||||||
|
it.getString(it.getColumnIndexOrThrow(Schema.Category.ROW_NAME))
|
||||||
|
}.toSet()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object InstalledAdapter {
|
||||||
|
|
||||||
|
fun getStream(packageName: String): Flow<InstalledItem?> = flowOf(Unit)
|
||||||
|
.onCompletion { if (it == null) emitAll(flowCollection(Subject.Products)) }
|
||||||
|
.map { get(packageName, null) }
|
||||||
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
|
fun get(packageName: String, signal: CancellationSignal?): InstalledItem? {
|
||||||
|
return db.query(
|
||||||
|
Schema.Installed.name,
|
||||||
|
columns = arrayOf(
|
||||||
|
Schema.Installed.ROW_PACKAGE_NAME,
|
||||||
|
Schema.Installed.ROW_VERSION,
|
||||||
|
Schema.Installed.ROW_VERSION_CODE,
|
||||||
|
Schema.Installed.ROW_SIGNATURE,
|
||||||
|
),
|
||||||
|
selection = Pair("${Schema.Installed.ROW_PACKAGE_NAME} = ?", arrayOf(packageName)),
|
||||||
|
signal = signal,
|
||||||
|
).use { it.firstOrNull()?.let(::transform) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun put(installedItem: InstalledItem, notify: Boolean) {
|
||||||
|
db.insertOrReplace(
|
||||||
|
true,
|
||||||
|
Schema.Installed.name,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(Schema.Installed.ROW_PACKAGE_NAME, installedItem.packageName)
|
||||||
|
put(Schema.Installed.ROW_VERSION, installedItem.version)
|
||||||
|
put(Schema.Installed.ROW_VERSION_CODE, installedItem.versionCode)
|
||||||
|
put(Schema.Installed.ROW_SIGNATURE, installedItem.signature)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if (notify) {
|
||||||
|
notifyChanged(Subject.Products)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun put(installedItem: InstalledItem) = put(installedItem, true)
|
||||||
|
|
||||||
|
fun putAll(installedItems: List<InstalledItem>) {
|
||||||
|
db.transaction {
|
||||||
|
db.delete(Schema.Installed.name, null, null)
|
||||||
|
installedItems.forEach { put(it, false) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun delete(packageName: String) {
|
||||||
|
val count = db.delete(
|
||||||
|
Schema.Installed.name,
|
||||||
|
"${Schema.Installed.ROW_PACKAGE_NAME} = ?",
|
||||||
|
arrayOf(packageName),
|
||||||
|
)
|
||||||
|
if (count > 0) {
|
||||||
|
notifyChanged(Subject.Products)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun transform(cursor: Cursor): InstalledItem {
|
||||||
|
return InstalledItem(
|
||||||
|
cursor.getString(cursor.getColumnIndexOrThrow(Schema.Installed.ROW_PACKAGE_NAME)),
|
||||||
|
cursor.getString(cursor.getColumnIndexOrThrow(Schema.Installed.ROW_VERSION)),
|
||||||
|
cursor.getLong(cursor.getColumnIndexOrThrow(Schema.Installed.ROW_VERSION_CODE)),
|
||||||
|
cursor.getString(cursor.getColumnIndexOrThrow(Schema.Installed.ROW_SIGNATURE)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object LockAdapter {
|
||||||
|
private fun put(lock: Pair<String, Long>, notify: Boolean) {
|
||||||
|
db.insertOrReplace(
|
||||||
|
true,
|
||||||
|
Schema.Lock.name,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(Schema.Lock.ROW_PACKAGE_NAME, lock.first)
|
||||||
|
put(Schema.Lock.ROW_VERSION_CODE, lock.second)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if (notify) {
|
||||||
|
notifyChanged(Subject.Products)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun put(lock: Pair<String, Long>) = put(lock, true)
|
||||||
|
|
||||||
|
fun putAll(locks: List<Pair<String, Long>>) {
|
||||||
|
db.transaction {
|
||||||
|
db.delete(Schema.Lock.name, null, null)
|
||||||
|
locks.forEach { put(it, false) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun delete(packageName: String) {
|
||||||
|
db.delete(Schema.Lock.name, "${Schema.Lock.ROW_PACKAGE_NAME} = ?", arrayOf(packageName))
|
||||||
|
notifyChanged(Subject.Products)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object UpdaterAdapter {
|
||||||
|
private val Table.temporaryName: String
|
||||||
|
get() = "${name}_temporary"
|
||||||
|
|
||||||
|
fun createTemporaryTable() {
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Product.temporaryName}")
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Category.temporaryName}")
|
||||||
|
db.execSQL(Schema.Product.formatCreateTable(Schema.Product.temporaryName))
|
||||||
|
db.execSQL(Schema.Category.formatCreateTable(Schema.Category.temporaryName))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun putTemporary(products: List<Product>) {
|
||||||
|
db.transaction {
|
||||||
|
for (product in products) {
|
||||||
|
// Format signatures like ".signature1.signature2." for easier select
|
||||||
|
val signatures = product.signatures.joinToString { ".$it" }
|
||||||
|
.let { if (it.isNotEmpty()) "$it." else "" }
|
||||||
|
db.insertOrReplace(
|
||||||
|
true,
|
||||||
|
Schema.Product.temporaryName,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(Schema.Product.ROW_REPOSITORY_ID, product.repositoryId)
|
||||||
|
put(Schema.Product.ROW_PACKAGE_NAME, product.packageName)
|
||||||
|
put(Schema.Product.ROW_NAME, product.name)
|
||||||
|
put(Schema.Product.ROW_SUMMARY, product.summary)
|
||||||
|
put(Schema.Product.ROW_DESCRIPTION, product.description)
|
||||||
|
put(Schema.Product.ROW_ADDED, product.added)
|
||||||
|
put(Schema.Product.ROW_UPDATED, product.updated)
|
||||||
|
put(Schema.Product.ROW_VERSION_CODE, product.versionCode)
|
||||||
|
put(Schema.Product.ROW_SIGNATURES, signatures)
|
||||||
|
put(Schema.Product.ROW_COMPATIBLE, if (product.compatible) 1 else 0)
|
||||||
|
put(Schema.Product.ROW_DATA, jsonGenerate(product::serialize))
|
||||||
|
put(
|
||||||
|
Schema.Product.ROW_DATA_ITEM,
|
||||||
|
jsonGenerate(product.item()::serialize),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
for (category in product.categories) {
|
||||||
|
db.insertOrReplace(
|
||||||
|
true,
|
||||||
|
Schema.Category.temporaryName,
|
||||||
|
ContentValues().apply {
|
||||||
|
put(Schema.Category.ROW_REPOSITORY_ID, product.repositoryId)
|
||||||
|
put(Schema.Category.ROW_PACKAGE_NAME, product.packageName)
|
||||||
|
put(Schema.Category.ROW_NAME, category)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun finishTemporary(repository: Repository, success: Boolean) {
|
||||||
|
if (success) {
|
||||||
|
db.transaction {
|
||||||
|
db.delete(
|
||||||
|
Schema.Product.name,
|
||||||
|
"${Schema.Product.ROW_REPOSITORY_ID} = ?",
|
||||||
|
arrayOf(repository.id.toString()),
|
||||||
|
)
|
||||||
|
db.delete(
|
||||||
|
Schema.Category.name,
|
||||||
|
"${Schema.Category.ROW_REPOSITORY_ID} = ?",
|
||||||
|
arrayOf(repository.id.toString()),
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"INSERT INTO ${Schema.Product.name} SELECT * " +
|
||||||
|
"FROM ${Schema.Product.temporaryName}",
|
||||||
|
)
|
||||||
|
db.execSQL(
|
||||||
|
"INSERT INTO ${Schema.Category.name} SELECT * " +
|
||||||
|
"FROM ${Schema.Category.temporaryName}",
|
||||||
|
)
|
||||||
|
RepositoryAdapter.putWithoutNotification(repository, true, db)
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Product.temporaryName}")
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Category.temporaryName}")
|
||||||
|
}
|
||||||
|
notifyChanged(
|
||||||
|
Subject.Repositories,
|
||||||
|
Subject.Repository(repository.id),
|
||||||
|
Subject.Products,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Product.temporaryName}")
|
||||||
|
db.execSQL("DROP TABLE IF EXISTS ${Schema.Category.temporaryName}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.database.ContentObservable
|
||||||
|
import android.database.ContentObserver
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.database.CursorWrapper
|
||||||
|
|
||||||
|
class ObservableCursor(
|
||||||
|
cursor: Cursor,
|
||||||
|
private val observable: (
|
||||||
|
register: Boolean,
|
||||||
|
observer: () -> Unit
|
||||||
|
) -> Unit
|
||||||
|
) : CursorWrapper(cursor) {
|
||||||
|
private var registered = false
|
||||||
|
private val contentObservable = ContentObservable()
|
||||||
|
|
||||||
|
private val onChange: () -> Unit = {
|
||||||
|
contentObservable.dispatchChange(false, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
observable(true, onChange)
|
||||||
|
registered = true
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun registerContentObserver(observer: ContentObserver) {
|
||||||
|
super.registerContentObserver(observer)
|
||||||
|
contentObservable.registerObserver(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun unregisterContentObserver(observer: ContentObserver) {
|
||||||
|
super.unregisterContentObserver(observer)
|
||||||
|
contentObservable.unregisterObserver(observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
override fun requery(): Boolean {
|
||||||
|
if (!registered) {
|
||||||
|
observable(true, onChange)
|
||||||
|
registered = true
|
||||||
|
}
|
||||||
|
return super.requery()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated("Deprecated in Java")
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
override fun deactivate() {
|
||||||
|
super.deactivate()
|
||||||
|
deactivateOrClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
super.close()
|
||||||
|
contentObservable.unregisterAll()
|
||||||
|
deactivateOrClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun deactivateOrClose() {
|
||||||
|
observable(false, onChange)
|
||||||
|
registered = false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.database.sqlite.SQLiteDatabase
|
||||||
|
import android.os.CancellationSignal
|
||||||
|
import com.looker.droidify.BuildConfig
|
||||||
|
import com.looker.droidify.utility.common.extension.asSequence
|
||||||
|
import com.looker.droidify.utility.common.log
|
||||||
|
|
||||||
|
class QueryBuilder {
|
||||||
|
|
||||||
|
private val builder = StringBuilder(256)
|
||||||
|
private val arguments = mutableListOf<String>()
|
||||||
|
|
||||||
|
operator fun plusAssign(query: String) {
|
||||||
|
if (builder.isNotEmpty()) {
|
||||||
|
builder.append(" ")
|
||||||
|
}
|
||||||
|
builder.trimAndJoin(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun remAssign(argument: String) {
|
||||||
|
this.arguments += argument
|
||||||
|
}
|
||||||
|
|
||||||
|
operator fun remAssign(arguments: List<String>) {
|
||||||
|
this.arguments += arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
fun query(db: SQLiteDatabase, signal: CancellationSignal?): Cursor {
|
||||||
|
val query = builder.toString()
|
||||||
|
val arguments = arguments.toTypedArray()
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
synchronized(QueryBuilder::class.java) {
|
||||||
|
log(query)
|
||||||
|
db.rawQuery("EXPLAIN QUERY PLAN $query", arguments).use {
|
||||||
|
it.asSequence()
|
||||||
|
.forEach { log(":: ${it.getString(it.getColumnIndex("detail"))}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return db.rawQuery(query, arguments, signal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun StringBuilder.trimAndJoin(
|
||||||
|
input: String,
|
||||||
|
) {
|
||||||
|
var isFirstLine = true
|
||||||
|
var startOfLine = 0
|
||||||
|
for (i in input.indices) {
|
||||||
|
val char = input[i]
|
||||||
|
when {
|
||||||
|
char == '\n' -> {
|
||||||
|
trimAndAppendLine(input, startOfLine, i, this, isFirstLine)
|
||||||
|
isFirstLine = false
|
||||||
|
startOfLine = i + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
if (i == input.lastIndex) {
|
||||||
|
trimAndAppendLine(input, startOfLine, i + 1, this, isFirstLine)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun trimAndAppendLine(
|
||||||
|
input: String,
|
||||||
|
start: Int,
|
||||||
|
end: Int,
|
||||||
|
builder: StringBuilder,
|
||||||
|
isFirstLine: Boolean,
|
||||||
|
) {
|
||||||
|
var lineStart = start
|
||||||
|
var lineEnd = end - 1
|
||||||
|
|
||||||
|
while (lineStart <= lineEnd && input[lineStart].isWhitespace()) {
|
||||||
|
lineStart++
|
||||||
|
}
|
||||||
|
|
||||||
|
while (lineEnd >= lineStart && input[lineEnd].isWhitespace()) {
|
||||||
|
lineEnd--
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lineStart <= lineEnd) {
|
||||||
|
if (!isFirstLine) {
|
||||||
|
builder.append(' ')
|
||||||
|
}
|
||||||
|
builder.append(input, lineStart, lineEnd + 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.database.Cursor
|
||||||
|
import android.os.CancellationSignal
|
||||||
|
import android.os.OperationCanceledException
|
||||||
|
import androidx.loader.content.AsyncTaskLoader
|
||||||
|
|
||||||
|
class QueryLoader(context: Context, private val query: (CancellationSignal) -> Cursor?) :
|
||||||
|
AsyncTaskLoader<Cursor>(context) {
|
||||||
|
private val observer = ForceLoadContentObserver()
|
||||||
|
private var cancellationSignal: CancellationSignal? = null
|
||||||
|
private var cursor: Cursor? = null
|
||||||
|
|
||||||
|
override fun loadInBackground(): Cursor? {
|
||||||
|
val cancellationSignal = synchronized(this) {
|
||||||
|
if (isLoadInBackgroundCanceled) {
|
||||||
|
throw OperationCanceledException()
|
||||||
|
}
|
||||||
|
val cancellationSignal = CancellationSignal()
|
||||||
|
this.cancellationSignal = cancellationSignal
|
||||||
|
cancellationSignal
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val cursor = query(cancellationSignal)
|
||||||
|
if (cursor != null) {
|
||||||
|
try {
|
||||||
|
cursor.count // Ensure the cursor window is filled
|
||||||
|
cursor.registerContentObserver(observer)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
cursor.close()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cursor
|
||||||
|
} finally {
|
||||||
|
synchronized(this) {
|
||||||
|
this.cancellationSignal = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun cancelLoadInBackground() {
|
||||||
|
super.cancelLoadInBackground()
|
||||||
|
|
||||||
|
synchronized(this) {
|
||||||
|
cancellationSignal?.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun deliverResult(data: Cursor?) {
|
||||||
|
if (isReset) {
|
||||||
|
data?.close()
|
||||||
|
} else {
|
||||||
|
val oldCursor = cursor
|
||||||
|
cursor = data
|
||||||
|
if (isStarted) {
|
||||||
|
super.deliverResult(data)
|
||||||
|
}
|
||||||
|
if (oldCursor != data) {
|
||||||
|
oldCursor.closeIfNeeded()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartLoading() {
|
||||||
|
cursor?.let(this::deliverResult)
|
||||||
|
if (takeContentChanged() || cursor == null) {
|
||||||
|
forceLoad()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStopLoading() {
|
||||||
|
cancelLoad()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCanceled(data: Cursor?) {
|
||||||
|
data.closeIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReset() {
|
||||||
|
super.onReset()
|
||||||
|
|
||||||
|
stopLoading()
|
||||||
|
cursor.closeIfNeeded()
|
||||||
|
cursor = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Cursor?.closeIfNeeded() {
|
||||||
|
if (this != null && !isClosed) {
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package com.looker.droidify.database
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import com.fasterxml.jackson.core.JsonToken
|
||||||
|
import com.looker.droidify.utility.common.Exporter
|
||||||
|
import com.looker.droidify.utility.common.extension.Json
|
||||||
|
import com.looker.droidify.utility.common.extension.forEach
|
||||||
|
import com.looker.droidify.utility.common.extension.forEachKey
|
||||||
|
import com.looker.droidify.utility.common.extension.parseDictionary
|
||||||
|
import com.looker.droidify.utility.common.extension.writeArray
|
||||||
|
import com.looker.droidify.utility.common.extension.writeDictionary
|
||||||
|
import com.looker.droidify.di.ApplicationScope
|
||||||
|
import com.looker.droidify.di.IoDispatcher
|
||||||
|
import com.looker.droidify.model.Repository
|
||||||
|
import com.looker.droidify.utility.serialization.repository
|
||||||
|
import com.looker.droidify.utility.serialization.serialize
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class RepositoryExporter @Inject constructor(
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
|
@ApplicationScope private val scope: CoroutineScope,
|
||||||
|
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
|
||||||
|
) : Exporter<List<Repository>> {
|
||||||
|
override suspend fun export(item: List<Repository>, target: Uri) {
|
||||||
|
scope.launch(ioDispatcher) {
|
||||||
|
val stream = context.contentResolver.openOutputStream(target)
|
||||||
|
Json.factory.createGenerator(stream).use { generator ->
|
||||||
|
generator.writeDictionary {
|
||||||
|
writeArray("repositories") {
|
||||||
|
item.map {
|
||||||
|
it.copy(
|
||||||
|
id = -1,
|
||||||
|
mirrors = if (it.enabled) it.mirrors else emptyList(),
|
||||||
|
lastModified = "",
|
||||||
|
entityTag = ""
|
||||||
|
)
|
||||||
|
}.forEach { repo ->
|
||||||
|
writeDictionary {
|
||||||
|
repo.serialize(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun import(target: Uri): List<Repository> = withContext(ioDispatcher) {
|
||||||
|
val list = mutableListOf<Repository>()
|
||||||
|
val stream = context.contentResolver.openInputStream(target)
|
||||||
|
Json.factory.createParser(stream).use { generator ->
|
||||||
|
generator?.parseDictionary {
|
||||||
|
forEachKey {
|
||||||
|
if (it.array("repositories")) {
|
||||||
|
forEach(JsonToken.START_OBJECT) {
|
||||||
|
val repo = repository()
|
||||||
|
list.add(repo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
package com.looker.droidify.datastore
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.core.IOException
|
||||||
|
import androidx.datastore.preferences.core.MutablePreferences
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||||
|
import androidx.datastore.preferences.core.edit
|
||||||
|
import androidx.datastore.preferences.core.intPreferencesKey
|
||||||
|
import androidx.datastore.preferences.core.longPreferencesKey
|
||||||
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
|
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||||
|
import com.looker.droidify.datastore.model.AutoSync
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.datastore.model.ProxyPreference
|
||||||
|
import com.looker.droidify.datastore.model.ProxyType
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.datastore.model.Theme
|
||||||
|
import com.looker.droidify.utility.common.Exporter
|
||||||
|
import com.looker.droidify.utility.common.extension.updateAsMutable
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.catch
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlin.time.Duration
|
||||||
|
import kotlin.time.Duration.Companion.hours
|
||||||
|
|
||||||
|
class PreferenceSettingsRepository(
|
||||||
|
private val dataStore: DataStore<Preferences>,
|
||||||
|
private val exporter: Exporter<Settings>,
|
||||||
|
) : SettingsRepository {
|
||||||
|
override val data: Flow<Settings> = dataStore.data
|
||||||
|
.catch { exception ->
|
||||||
|
if (exception is IOException) {
|
||||||
|
Log.e("TAG", "Error reading preferences.", exception)
|
||||||
|
} else {
|
||||||
|
throw exception
|
||||||
|
}
|
||||||
|
}.map(::mapSettings)
|
||||||
|
|
||||||
|
override suspend fun getInitial(): Settings {
|
||||||
|
return data.first()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun export(target: Uri) {
|
||||||
|
val currentSettings = getInitial()
|
||||||
|
exporter.export(currentSettings, target)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun import(target: Uri) {
|
||||||
|
val importedSettings = exporter.import(target)
|
||||||
|
val updatedFavorites = importedSettings.favouriteApps +
|
||||||
|
getInitial().favouriteApps
|
||||||
|
val updatedSettings = importedSettings.copy(favouriteApps = updatedFavorites)
|
||||||
|
dataStore.edit {
|
||||||
|
it.setting(updatedSettings)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun setLanguage(language: String) =
|
||||||
|
LANGUAGE.update(language)
|
||||||
|
|
||||||
|
override suspend fun enableIncompatibleVersion(enable: Boolean) =
|
||||||
|
INCOMPATIBLE_VERSIONS.update(enable)
|
||||||
|
|
||||||
|
override suspend fun enableNotifyUpdates(enable: Boolean) =
|
||||||
|
NOTIFY_UPDATES.update(enable)
|
||||||
|
|
||||||
|
override suspend fun enableUnstableUpdates(enable: Boolean) =
|
||||||
|
UNSTABLE_UPDATES.update(enable)
|
||||||
|
|
||||||
|
override suspend fun setIgnoreSignature(enable: Boolean) =
|
||||||
|
IGNORE_SIGNATURE.update(enable)
|
||||||
|
|
||||||
|
override suspend fun setTheme(theme: Theme) =
|
||||||
|
THEME.update(theme.name)
|
||||||
|
|
||||||
|
override suspend fun setDynamicTheme(enable: Boolean) =
|
||||||
|
DYNAMIC_THEME.update(enable)
|
||||||
|
|
||||||
|
override suspend fun setInstallerType(installerType: InstallerType) =
|
||||||
|
INSTALLER_TYPE.update(installerType.name)
|
||||||
|
|
||||||
|
override suspend fun setAutoUpdate(allow: Boolean) =
|
||||||
|
AUTO_UPDATE.update(allow)
|
||||||
|
|
||||||
|
override suspend fun setAutoSync(autoSync: AutoSync) =
|
||||||
|
AUTO_SYNC.update(autoSync.name)
|
||||||
|
|
||||||
|
override suspend fun setSortOrder(sortOrder: SortOrder) =
|
||||||
|
SORT_ORDER.update(sortOrder.name)
|
||||||
|
|
||||||
|
override suspend fun setProxyType(proxyType: ProxyType) =
|
||||||
|
PROXY_TYPE.update(proxyType.name)
|
||||||
|
|
||||||
|
override suspend fun setProxyHost(proxyHost: String) =
|
||||||
|
PROXY_HOST.update(proxyHost)
|
||||||
|
|
||||||
|
override suspend fun setProxyPort(proxyPort: Int) =
|
||||||
|
PROXY_PORT.update(proxyPort)
|
||||||
|
|
||||||
|
override suspend fun setCleanUpInterval(interval: Duration) =
|
||||||
|
CLEAN_UP_INTERVAL.update(interval.inWholeHours)
|
||||||
|
|
||||||
|
override suspend fun setCleanupInstant() =
|
||||||
|
LAST_CLEAN_UP.update(Clock.System.now().toEpochMilliseconds())
|
||||||
|
|
||||||
|
override suspend fun setHomeScreenSwiping(value: Boolean) =
|
||||||
|
HOME_SCREEN_SWIPING.update(value)
|
||||||
|
|
||||||
|
override suspend fun toggleFavourites(packageName: String) {
|
||||||
|
dataStore.edit { preference ->
|
||||||
|
val currentSet = preference[FAVOURITE_APPS] ?: emptySet()
|
||||||
|
val newSet = currentSet.updateAsMutable {
|
||||||
|
if (!add(packageName)) remove(packageName)
|
||||||
|
}
|
||||||
|
preference[FAVOURITE_APPS] = newSet
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapSettings(preferences: Preferences): Settings {
|
||||||
|
val installerType =
|
||||||
|
InstallerType.valueOf(preferences[INSTALLER_TYPE] ?: InstallerType.Default.name)
|
||||||
|
|
||||||
|
val language = preferences[LANGUAGE] ?: "system"
|
||||||
|
val incompatibleVersions = preferences[INCOMPATIBLE_VERSIONS] ?: false
|
||||||
|
val notifyUpdate = preferences[NOTIFY_UPDATES] ?: true
|
||||||
|
val unstableUpdate = preferences[UNSTABLE_UPDATES] ?: false
|
||||||
|
val ignoreSignature = preferences[IGNORE_SIGNATURE] ?: false
|
||||||
|
val theme = Theme.valueOf(preferences[THEME] ?: Theme.SYSTEM.name)
|
||||||
|
val dynamicTheme = preferences[DYNAMIC_THEME] ?: false
|
||||||
|
val autoUpdate = preferences[AUTO_UPDATE] ?: false
|
||||||
|
val autoSync = AutoSync.valueOf(preferences[AUTO_SYNC] ?: AutoSync.WIFI_ONLY.name)
|
||||||
|
val sortOrder = SortOrder.valueOf(preferences[SORT_ORDER] ?: SortOrder.UPDATED.name)
|
||||||
|
val type = ProxyType.valueOf(preferences[PROXY_TYPE] ?: ProxyType.DIRECT.name)
|
||||||
|
val host = preferences[PROXY_HOST] ?: "localhost"
|
||||||
|
val port = preferences[PROXY_PORT] ?: 9050
|
||||||
|
val proxy = ProxyPreference(type = type, host = host, port = port)
|
||||||
|
val cleanUpInterval = preferences[CLEAN_UP_INTERVAL]?.hours ?: 12L.hours
|
||||||
|
val lastCleanup = preferences[LAST_CLEAN_UP]?.let { Instant.fromEpochMilliseconds(it) }
|
||||||
|
val favouriteApps = preferences[FAVOURITE_APPS] ?: emptySet()
|
||||||
|
val homeScreenSwiping = preferences[HOME_SCREEN_SWIPING] ?: true
|
||||||
|
|
||||||
|
return Settings(
|
||||||
|
language = language,
|
||||||
|
incompatibleVersions = incompatibleVersions,
|
||||||
|
notifyUpdate = notifyUpdate,
|
||||||
|
unstableUpdate = unstableUpdate,
|
||||||
|
ignoreSignature = ignoreSignature,
|
||||||
|
theme = theme,
|
||||||
|
dynamicTheme = dynamicTheme,
|
||||||
|
installerType = installerType,
|
||||||
|
autoUpdate = autoUpdate,
|
||||||
|
autoSync = autoSync,
|
||||||
|
sortOrder = sortOrder,
|
||||||
|
proxy = proxy,
|
||||||
|
cleanUpInterval = cleanUpInterval,
|
||||||
|
lastCleanup = lastCleanup,
|
||||||
|
favouriteApps = favouriteApps,
|
||||||
|
homeScreenSwiping = homeScreenSwiping,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend inline fun <T> Preferences.Key<T>.update(newValue: T) {
|
||||||
|
dataStore.edit { preferences ->
|
||||||
|
preferences[this] = newValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object PreferencesKeys {
|
||||||
|
val LANGUAGE = stringPreferencesKey("key_language")
|
||||||
|
val INCOMPATIBLE_VERSIONS = booleanPreferencesKey("key_incompatible_versions")
|
||||||
|
val NOTIFY_UPDATES = booleanPreferencesKey("key_notify_updates")
|
||||||
|
val UNSTABLE_UPDATES = booleanPreferencesKey("key_unstable_updates")
|
||||||
|
val IGNORE_SIGNATURE = booleanPreferencesKey("key_ignore_signature")
|
||||||
|
val DYNAMIC_THEME = booleanPreferencesKey("key_dynamic_theme")
|
||||||
|
val AUTO_UPDATE = booleanPreferencesKey("key_auto_updates")
|
||||||
|
val PROXY_HOST = stringPreferencesKey("key_proxy_host")
|
||||||
|
val PROXY_PORT = intPreferencesKey("key_proxy_port")
|
||||||
|
val CLEAN_UP_INTERVAL = longPreferencesKey("key_clean_up_interval")
|
||||||
|
val LAST_CLEAN_UP = longPreferencesKey("key_last_clean_up_time")
|
||||||
|
val FAVOURITE_APPS = stringSetPreferencesKey("key_favourite_apps")
|
||||||
|
val HOME_SCREEN_SWIPING = booleanPreferencesKey("key_home_swiping")
|
||||||
|
|
||||||
|
// Enums
|
||||||
|
val THEME = stringPreferencesKey("key_theme")
|
||||||
|
val INSTALLER_TYPE = stringPreferencesKey("key_installer_type")
|
||||||
|
val AUTO_SYNC = stringPreferencesKey("key_auto_sync")
|
||||||
|
val SORT_ORDER = stringPreferencesKey("key_sort_order")
|
||||||
|
val PROXY_TYPE = stringPreferencesKey("key_proxy_type")
|
||||||
|
|
||||||
|
fun MutablePreferences.setting(settings: Settings): Preferences {
|
||||||
|
set(LANGUAGE, settings.language)
|
||||||
|
set(INCOMPATIBLE_VERSIONS, settings.incompatibleVersions)
|
||||||
|
set(NOTIFY_UPDATES, settings.notifyUpdate)
|
||||||
|
set(UNSTABLE_UPDATES, settings.unstableUpdate)
|
||||||
|
set(THEME, settings.theme.name)
|
||||||
|
set(DYNAMIC_THEME, settings.dynamicTheme)
|
||||||
|
set(INSTALLER_TYPE, settings.installerType.name)
|
||||||
|
set(AUTO_UPDATE, settings.autoUpdate)
|
||||||
|
set(AUTO_SYNC, settings.autoSync.name)
|
||||||
|
set(SORT_ORDER, settings.sortOrder.name)
|
||||||
|
set(PROXY_TYPE, settings.proxy.type.name)
|
||||||
|
set(PROXY_HOST, settings.proxy.host)
|
||||||
|
set(PROXY_PORT, settings.proxy.port)
|
||||||
|
set(CLEAN_UP_INTERVAL, settings.cleanUpInterval.inWholeHours)
|
||||||
|
set(LAST_CLEAN_UP, settings.lastCleanup?.toEpochMilliseconds() ?: 0L)
|
||||||
|
set(FAVOURITE_APPS, settings.favouriteApps)
|
||||||
|
set(HOME_SCREEN_SWIPING, settings.homeScreenSwiping)
|
||||||
|
return this.toPreferences()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package com.looker.droidify.datastore
|
||||||
|
|
||||||
|
import androidx.datastore.core.Serializer
|
||||||
|
import com.looker.droidify.datastore.model.AutoSync
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.datastore.model.ProxyPreference
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.datastore.model.Theme
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import kotlin.time.Duration
|
||||||
|
import kotlin.time.Duration.Companion.hours
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.ExperimentalSerializationApi
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.decodeFromStream
|
||||||
|
import kotlinx.serialization.json.encodeToStream
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Settings(
|
||||||
|
val language: String = "system",
|
||||||
|
val incompatibleVersions: Boolean = false,
|
||||||
|
val notifyUpdate: Boolean = true,
|
||||||
|
val unstableUpdate: Boolean = false,
|
||||||
|
val ignoreSignature: Boolean = false,
|
||||||
|
val theme: Theme = Theme.SYSTEM,
|
||||||
|
val dynamicTheme: Boolean = false,
|
||||||
|
val installerType: InstallerType = InstallerType.Default,
|
||||||
|
val autoUpdate: Boolean = false,
|
||||||
|
val autoSync: AutoSync = AutoSync.WIFI_ONLY,
|
||||||
|
val sortOrder: SortOrder = SortOrder.UPDATED,
|
||||||
|
val proxy: ProxyPreference = ProxyPreference(),
|
||||||
|
val cleanUpInterval: Duration = 12.hours,
|
||||||
|
val lastCleanup: Instant? = null,
|
||||||
|
val favouriteApps: Set<String> = emptySet(),
|
||||||
|
val homeScreenSwiping: Boolean = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
@OptIn(ExperimentalSerializationApi::class)
|
||||||
|
object SettingsSerializer : Serializer<Settings> {
|
||||||
|
|
||||||
|
private val json = Json { encodeDefaults = true }
|
||||||
|
|
||||||
|
override val defaultValue: Settings = Settings()
|
||||||
|
|
||||||
|
override suspend fun readFrom(input: InputStream): Settings {
|
||||||
|
return try {
|
||||||
|
json.decodeFromStream(input)
|
||||||
|
} catch (e: SerializationException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
defaultValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun writeTo(t: Settings, output: OutputStream) {
|
||||||
|
try {
|
||||||
|
json.encodeToStream(t, output)
|
||||||
|
} catch (e: SerializationException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package com.looker.droidify.datastore
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import com.looker.droidify.datastore.model.AutoSync
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.datastore.model.ProxyType
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.datastore.model.Theme
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlin.time.Duration
|
||||||
|
|
||||||
|
interface SettingsRepository {
|
||||||
|
|
||||||
|
val data: Flow<Settings>
|
||||||
|
|
||||||
|
suspend fun getInitial(): Settings
|
||||||
|
|
||||||
|
suspend fun export(target: Uri)
|
||||||
|
|
||||||
|
suspend fun import(target: Uri)
|
||||||
|
|
||||||
|
suspend fun setLanguage(language: String)
|
||||||
|
|
||||||
|
suspend fun enableIncompatibleVersion(enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun enableNotifyUpdates(enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun enableUnstableUpdates(enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun setIgnoreSignature(enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun setTheme(theme: Theme)
|
||||||
|
|
||||||
|
suspend fun setDynamicTheme(enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun setInstallerType(installerType: InstallerType)
|
||||||
|
|
||||||
|
suspend fun setAutoUpdate(allow: Boolean)
|
||||||
|
|
||||||
|
suspend fun setAutoSync(autoSync: AutoSync)
|
||||||
|
|
||||||
|
suspend fun setSortOrder(sortOrder: SortOrder)
|
||||||
|
|
||||||
|
suspend fun setProxyType(proxyType: ProxyType)
|
||||||
|
|
||||||
|
suspend fun setProxyHost(proxyHost: String)
|
||||||
|
|
||||||
|
suspend fun setProxyPort(proxyPort: Int)
|
||||||
|
|
||||||
|
suspend fun setCleanUpInterval(interval: Duration)
|
||||||
|
|
||||||
|
suspend fun setCleanupInstant()
|
||||||
|
|
||||||
|
suspend fun setHomeScreenSwiping(value: Boolean)
|
||||||
|
|
||||||
|
suspend fun toggleFavourites(packageName: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <T> SettingsRepository.get(crossinline block: suspend Settings.() -> T): Flow<T> {
|
||||||
|
return data.map(block).distinctUntilChanged()
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.looker.droidify.datastore.exporter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import com.looker.droidify.utility.common.Exporter
|
||||||
|
import com.looker.droidify.datastore.Settings
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.serialization.ExperimentalSerializationApi
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.decodeFromStream
|
||||||
|
import kotlinx.serialization.json.encodeToStream
|
||||||
|
import java.io.IOException
|
||||||
|
|
||||||
|
@OptIn(ExperimentalSerializationApi::class)
|
||||||
|
class SettingsExporter(
|
||||||
|
private val context: Context,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val ioDispatcher: CoroutineDispatcher,
|
||||||
|
private val json: Json
|
||||||
|
) : Exporter<Settings> {
|
||||||
|
|
||||||
|
override suspend fun export(item: Settings, target: Uri) {
|
||||||
|
scope.launch(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
context.contentResolver.openOutputStream(target).use {
|
||||||
|
if (it != null) json.encodeToStream(item, it)
|
||||||
|
}
|
||||||
|
} catch (e: SerializationException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
cancel()
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun import(target: Uri): Settings = withContext(ioDispatcher) {
|
||||||
|
try {
|
||||||
|
context.contentResolver.openInputStream(target).use {
|
||||||
|
checkNotNull(it) { "Null input stream for import file" }
|
||||||
|
json.decodeFromStream(it)
|
||||||
|
}
|
||||||
|
} catch (e: SerializationException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
throw IllegalStateException(e.message)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
throw IllegalStateException(e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package com.looker.droidify.datastore.extension
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import com.looker.droidify.R
|
||||||
|
import com.looker.droidify.R.string as stringRes
|
||||||
|
import com.looker.droidify.R.style as styleRes
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.datastore.model.AutoSync
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.datastore.model.ProxyType
|
||||||
|
import com.looker.droidify.datastore.model.SortOrder
|
||||||
|
import com.looker.droidify.datastore.model.Theme
|
||||||
|
import kotlin.time.Duration
|
||||||
|
|
||||||
|
fun Configuration.getThemeRes(theme: Theme, dynamicTheme: Boolean) = when (theme) {
|
||||||
|
Theme.SYSTEM -> {
|
||||||
|
if ((uiMode and Configuration.UI_MODE_NIGHT_YES) != 0) {
|
||||||
|
if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicDark
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Dark
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicLight
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Light
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Theme.SYSTEM_BLACK -> {
|
||||||
|
if ((uiMode and Configuration.UI_MODE_NIGHT_YES) != 0) {
|
||||||
|
if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicAmoled
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Amoled
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicLight
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Light
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Theme.LIGHT -> if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicLight
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Light
|
||||||
|
}
|
||||||
|
Theme.DARK -> if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicDark
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Dark
|
||||||
|
}
|
||||||
|
Theme.AMOLED -> if (SdkCheck.isSnowCake && dynamicTheme) {
|
||||||
|
styleRes.Theme_Main_DynamicAmoled
|
||||||
|
} else {
|
||||||
|
styleRes.Theme_Main_Amoled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Context?.toTime(duration: Duration): String {
|
||||||
|
val time = duration.inWholeHours.toInt()
|
||||||
|
val days = duration.inWholeDays.toInt()
|
||||||
|
if (duration == Duration.INFINITE) return this?.getString(stringRes.never) ?: ""
|
||||||
|
return if (time >= 24) {
|
||||||
|
"$days " + this?.resources?.getQuantityString(
|
||||||
|
R.plurals.days,
|
||||||
|
days
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
"$time " + this?.resources?.getQuantityString(R.plurals.hours, time)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Context?.themeName(theme: Theme) = this?.let {
|
||||||
|
when (theme) {
|
||||||
|
Theme.SYSTEM -> getString(stringRes.system)
|
||||||
|
Theme.SYSTEM_BLACK -> getString(stringRes.system) + " " + getString(stringRes.amoled)
|
||||||
|
Theme.LIGHT -> getString(stringRes.light)
|
||||||
|
Theme.DARK -> getString(stringRes.dark)
|
||||||
|
Theme.AMOLED -> getString(stringRes.amoled)
|
||||||
|
}
|
||||||
|
} ?: ""
|
||||||
|
|
||||||
|
fun Context?.sortOrderName(sortOrder: SortOrder) = this?.let {
|
||||||
|
when (sortOrder) {
|
||||||
|
SortOrder.UPDATED -> getString(stringRes.recently_updated)
|
||||||
|
SortOrder.ADDED -> getString(stringRes.whats_new)
|
||||||
|
SortOrder.NAME -> getString(stringRes.name)
|
||||||
|
// SortOrder.SIZE -> getString(stringRes.size)
|
||||||
|
}
|
||||||
|
} ?: ""
|
||||||
|
|
||||||
|
fun Context?.autoSyncName(autoSync: AutoSync) = this?.let {
|
||||||
|
when (autoSync) {
|
||||||
|
AutoSync.NEVER -> getString(stringRes.never)
|
||||||
|
AutoSync.WIFI_ONLY -> getString(stringRes.only_on_wifi)
|
||||||
|
AutoSync.WIFI_PLUGGED_IN -> getString(stringRes.only_on_wifi_with_charging)
|
||||||
|
AutoSync.ALWAYS -> getString(stringRes.always)
|
||||||
|
}
|
||||||
|
} ?: ""
|
||||||
|
|
||||||
|
fun Context?.proxyName(proxyType: ProxyType) = this?.let {
|
||||||
|
when (proxyType) {
|
||||||
|
ProxyType.DIRECT -> getString(stringRes.no_proxy)
|
||||||
|
ProxyType.HTTP -> getString(stringRes.http_proxy)
|
||||||
|
ProxyType.SOCKS -> getString(stringRes.socks_proxy)
|
||||||
|
}
|
||||||
|
} ?: ""
|
||||||
|
|
||||||
|
fun Context?.installerName(installerType: InstallerType) = this?.let {
|
||||||
|
when (installerType) {
|
||||||
|
InstallerType.LEGACY -> getString(stringRes.legacy_installer)
|
||||||
|
InstallerType.SESSION -> getString(stringRes.session_installer)
|
||||||
|
InstallerType.SHIZUKU -> getString(stringRes.shizuku_installer)
|
||||||
|
InstallerType.ROOT -> getString(stringRes.root_installer)
|
||||||
|
}
|
||||||
|
} ?: ""
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.looker.droidify.datastore.migration
|
||||||
|
|
||||||
|
import com.looker.droidify.datastore.PreferenceSettingsRepository.PreferencesKeys.setting
|
||||||
|
import com.looker.droidify.datastore.Settings
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
|
||||||
|
class ProtoToPreferenceMigration(
|
||||||
|
private val oldDataStore: androidx.datastore.core.DataStore<Settings>
|
||||||
|
) : androidx.datastore.core.DataMigration<androidx.datastore.preferences.core.Preferences> {
|
||||||
|
override suspend fun cleanUp() {
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shouldMigrate(currentData: androidx.datastore.preferences.core.Preferences): Boolean {
|
||||||
|
return currentData.asMap().isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun migrate(currentData: androidx.datastore.preferences.core.Preferences): androidx.datastore.preferences.core.Preferences {
|
||||||
|
val settings = oldDataStore.data.first()
|
||||||
|
val preferences = currentData.toMutablePreferences()
|
||||||
|
preferences.setting(settings)
|
||||||
|
return preferences
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
enum class AutoSync {
|
||||||
|
ALWAYS,
|
||||||
|
WIFI_ONLY,
|
||||||
|
WIFI_PLUGGED_IN,
|
||||||
|
NEVER
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
import com.looker.droidify.utility.common.device.Miui
|
||||||
|
|
||||||
|
enum class InstallerType {
|
||||||
|
LEGACY,
|
||||||
|
SESSION,
|
||||||
|
SHIZUKU,
|
||||||
|
ROOT;
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val Default: InstallerType
|
||||||
|
get() = if (Miui.isMiui) {
|
||||||
|
if (Miui.isMiuiOptimizationDisabled()) SESSION else LEGACY
|
||||||
|
} else {
|
||||||
|
SESSION
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ProxyPreference(
|
||||||
|
val type: ProxyType = ProxyType.DIRECT,
|
||||||
|
val host: String = "localhost",
|
||||||
|
val port: Int = 9050
|
||||||
|
) {
|
||||||
|
fun update(
|
||||||
|
newType: ProxyType? = null,
|
||||||
|
newHost: String? = null,
|
||||||
|
newPort: Int? = null
|
||||||
|
): ProxyPreference = copy(
|
||||||
|
type = newType ?: type,
|
||||||
|
host = newHost ?: host,
|
||||||
|
port = newPort ?: port
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
enum class ProxyType {
|
||||||
|
DIRECT,
|
||||||
|
HTTP,
|
||||||
|
SOCKS
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
// todo: Add Support for sorting by size
|
||||||
|
enum class SortOrder {
|
||||||
|
UPDATED,
|
||||||
|
ADDED,
|
||||||
|
NAME
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.looker.droidify.datastore.model
|
||||||
|
|
||||||
|
enum class Theme {
|
||||||
|
SYSTEM,
|
||||||
|
SYSTEM_BLACK,
|
||||||
|
LIGHT,
|
||||||
|
DARK,
|
||||||
|
AMOLED
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.looker.droidify.di
|
||||||
|
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import javax.inject.Qualifier
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class IoDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class DefaultDispatcher
|
||||||
|
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@Qualifier
|
||||||
|
annotation class ApplicationScope
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object CoroutinesModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@IoDispatcher
|
||||||
|
fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@DefaultDispatcher
|
||||||
|
fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
@ApplicationScope
|
||||||
|
fun providesCoroutineScope(
|
||||||
|
@DefaultDispatcher dispatcher: CoroutineDispatcher
|
||||||
|
): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher)
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package com.looker.droidify.di
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.core.DataStoreFactory
|
||||||
|
import androidx.datastore.dataStoreFile
|
||||||
|
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import androidx.datastore.preferences.preferencesDataStoreFile
|
||||||
|
import com.looker.droidify.utility.common.Exporter
|
||||||
|
import com.looker.droidify.datastore.PreferenceSettingsRepository
|
||||||
|
import com.looker.droidify.datastore.Settings
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.datastore.SettingsSerializer
|
||||||
|
import com.looker.droidify.datastore.exporter.SettingsExporter
|
||||||
|
import com.looker.droidify.datastore.migration.ProtoToPreferenceMigration
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
private const val PREFERENCES = "settings_file"
|
||||||
|
|
||||||
|
private const val SETTINGS = "settings"
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object DatastoreModule {
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideProtoDatastore(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
): DataStore<Settings> = DataStoreFactory.create(
|
||||||
|
serializer = SettingsSerializer,
|
||||||
|
) {
|
||||||
|
context.dataStoreFile(PREFERENCES)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun providePreferenceDatastore(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
oldDatastore: DataStore<Settings>,
|
||||||
|
): DataStore<Preferences> = PreferenceDataStoreFactory.create(
|
||||||
|
migrations = listOf(
|
||||||
|
ProtoToPreferenceMigration(oldDatastore)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
context.preferencesDataStoreFile(SETTINGS)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideSettingsExporter(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
@ApplicationScope scope: CoroutineScope,
|
||||||
|
@IoDispatcher dispatcher: CoroutineDispatcher
|
||||||
|
): Exporter<Settings> = SettingsExporter(
|
||||||
|
context = context,
|
||||||
|
scope = scope,
|
||||||
|
ioDispatcher = dispatcher,
|
||||||
|
json = Json {
|
||||||
|
encodeDefaults = true
|
||||||
|
prettyPrint = true
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideSettingsRepository(
|
||||||
|
dataStore: DataStore<Preferences>,
|
||||||
|
exporter: Exporter<Settings>
|
||||||
|
): SettingsRepository = PreferenceSettingsRepository(dataStore, exporter)
|
||||||
|
}
|
||||||
23
app/src/main/kotlin/com/looker/droidify/di/InstallModule.kt
Normal file
23
app/src/main/kotlin/com/looker/droidify/di/InstallModule.kt
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package com.looker.droidify.di
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.installer.InstallManager
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object InstallModule {
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun providesInstaller(
|
||||||
|
@ApplicationContext context: Context,
|
||||||
|
settingsRepository: SettingsRepository
|
||||||
|
): InstallManager = InstallManager(context, settingsRepository)
|
||||||
|
}
|
||||||
27
app/src/main/kotlin/com/looker/droidify/di/NetworkModule.kt
Normal file
27
app/src/main/kotlin/com/looker/droidify/di/NetworkModule.kt
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package com.looker.droidify.di
|
||||||
|
|
||||||
|
import com.looker.droidify.network.Downloader
|
||||||
|
import com.looker.droidify.network.KtorDownloader
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import io.ktor.client.engine.okhttp.OkHttp
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object NetworkModule {
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
@Provides
|
||||||
|
fun provideDownloader(
|
||||||
|
@IoDispatcher
|
||||||
|
dispatcher: CoroutineDispatcher
|
||||||
|
): Downloader = KtorDownloader(
|
||||||
|
httpClientEngine = OkHttp.create(),
|
||||||
|
dispatcher = dispatcher,
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.looker.droidify.domain
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.App
|
||||||
|
import com.looker.droidify.domain.model.AppMinimal
|
||||||
|
import com.looker.droidify.domain.model.Author
|
||||||
|
import com.looker.droidify.domain.model.Package
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
|
interface AppRepository {
|
||||||
|
|
||||||
|
fun getApps(): Flow<List<AppMinimal>>
|
||||||
|
|
||||||
|
fun getApp(packageName: PackageName): Flow<List<App>>
|
||||||
|
|
||||||
|
fun getAppFromAuthor(author: Author): Flow<List<App>>
|
||||||
|
|
||||||
|
fun getPackages(packageName: PackageName): Flow<List<Package>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* returns true is the app is added successfully
|
||||||
|
* returns false if the app was already in the favourites and so it is removed
|
||||||
|
*/
|
||||||
|
suspend fun addToFavourite(packageName: PackageName): Boolean
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.looker.droidify.domain
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.Repo
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
|
||||||
|
interface RepoRepository {
|
||||||
|
|
||||||
|
suspend fun getRepo(id: Long): Repo?
|
||||||
|
|
||||||
|
fun getRepos(): Flow<List<Repo>>
|
||||||
|
|
||||||
|
suspend fun updateRepo(repo: Repo)
|
||||||
|
|
||||||
|
suspend fun enableRepository(repo: Repo, enable: Boolean)
|
||||||
|
|
||||||
|
suspend fun sync(repo: Repo): Boolean
|
||||||
|
|
||||||
|
suspend fun syncAll(): Boolean
|
||||||
|
}
|
||||||
83
app/src/main/kotlin/com/looker/droidify/domain/model/App.kt
Normal file
83
app/src/main/kotlin/com/looker/droidify/domain/model/App.kt
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
data class App(
|
||||||
|
val repoId: Long,
|
||||||
|
val appId: Long,
|
||||||
|
val categories: List<String>,
|
||||||
|
val links: Links,
|
||||||
|
val metadata: Metadata,
|
||||||
|
val author: Author,
|
||||||
|
val screenshots: Screenshots,
|
||||||
|
val graphics: Graphics,
|
||||||
|
val donation: Donation,
|
||||||
|
val preferredSigner: String = "",
|
||||||
|
val packages: List<Package>
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Author(
|
||||||
|
val id: Long,
|
||||||
|
val name: String,
|
||||||
|
val email: String,
|
||||||
|
val web: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Donation(
|
||||||
|
val regularUrl: String? = null,
|
||||||
|
val bitcoinAddress: String? = null,
|
||||||
|
val flattrId: String? = null,
|
||||||
|
val liteCoinAddress: String? = null,
|
||||||
|
val openCollectiveId: String? = null,
|
||||||
|
val librePayId: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Graphics(
|
||||||
|
val featureGraphic: String = "",
|
||||||
|
val promoGraphic: String = "",
|
||||||
|
val tvBanner: String = "",
|
||||||
|
val video: String = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Links(
|
||||||
|
val changelog: String = "",
|
||||||
|
val issueTracker: String = "",
|
||||||
|
val sourceCode: String = "",
|
||||||
|
val translation: String = "",
|
||||||
|
val webSite: String = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Metadata(
|
||||||
|
val name: String,
|
||||||
|
val packageName: PackageName,
|
||||||
|
val added: Long,
|
||||||
|
val description: String,
|
||||||
|
val icon: String,
|
||||||
|
val lastUpdated: Long,
|
||||||
|
val license: String,
|
||||||
|
val suggestedVersionCode: Long,
|
||||||
|
val suggestedVersionName: String,
|
||||||
|
val summary: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Screenshots(
|
||||||
|
val phone: List<String> = emptyList(),
|
||||||
|
val sevenInch: List<String> = emptyList(),
|
||||||
|
val tenInch: List<String> = emptyList(),
|
||||||
|
val tv: List<String> = emptyList(),
|
||||||
|
val wear: List<String> = emptyList()
|
||||||
|
)
|
||||||
|
|
||||||
|
data class AppMinimal(
|
||||||
|
val appId: Long,
|
||||||
|
val name: String,
|
||||||
|
val summary: String,
|
||||||
|
val icon: String,
|
||||||
|
val suggestedVersion: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun App.minimal() = AppMinimal(
|
||||||
|
appId = appId,
|
||||||
|
name = metadata.name,
|
||||||
|
summary = metadata.summary,
|
||||||
|
icon = metadata.icon,
|
||||||
|
suggestedVersion = metadata.suggestedVersionName,
|
||||||
|
)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
interface DataFile {
|
||||||
|
val name: String
|
||||||
|
val hash: String
|
||||||
|
val size: Long
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.security.cert.Certificate
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
@JvmInline
|
||||||
|
value class Fingerprint(val value: String) {
|
||||||
|
init {
|
||||||
|
require(value.isNotBlank() && value.length == FINGERPRINT_LENGTH) { "Invalid Fingerprint: $value" }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = value
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
|
inline fun Fingerprint.check(found: Fingerprint): Boolean {
|
||||||
|
return found.value.equals(value, ignoreCase = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val FINGERPRINT_LENGTH = 64
|
||||||
|
|
||||||
|
fun ByteArray.hex(): String = joinToString(separator = "") { byte ->
|
||||||
|
"%02x".format(Locale.US, byte.toInt() and 0xff)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Fingerprint.formattedString(): String = value.windowed(2, 2, false)
|
||||||
|
.take(FINGERPRINT_LENGTH / 2).joinToString(separator = " ") { it.uppercase(Locale.US) }
|
||||||
|
|
||||||
|
fun Certificate.fingerprint(): Fingerprint {
|
||||||
|
val bytes = encoded
|
||||||
|
return if (bytes.size >= 256) {
|
||||||
|
try {
|
||||||
|
val fingerprint = MessageDigest.getInstance("sha256").digest(bytes)
|
||||||
|
Fingerprint(fingerprint.hex().uppercase())
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
Fingerprint("")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Fingerprint("")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
data class Package(
|
||||||
|
val id: Long,
|
||||||
|
val installed: Boolean,
|
||||||
|
val added: Long,
|
||||||
|
val apk: ApkFile,
|
||||||
|
val platforms: Platforms,
|
||||||
|
val features: List<String>,
|
||||||
|
val antiFeatures: List<String>,
|
||||||
|
val manifest: Manifest,
|
||||||
|
val whatsNew: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ApkFile(
|
||||||
|
override val name: String,
|
||||||
|
override val hash: String,
|
||||||
|
override val size: Long
|
||||||
|
) : DataFile
|
||||||
|
|
||||||
|
data class Manifest(
|
||||||
|
val versionCode: Long,
|
||||||
|
val versionName: String,
|
||||||
|
val usesSDKs: SDKs,
|
||||||
|
val signer: Set<String>,
|
||||||
|
val permissions: List<Permission>
|
||||||
|
)
|
||||||
|
|
||||||
|
@JvmInline
|
||||||
|
value class Platforms(val value: List<String>)
|
||||||
|
|
||||||
|
data class SDKs(
|
||||||
|
val min: Int = -1,
|
||||||
|
val max: Int = -1,
|
||||||
|
val target: Int = -1
|
||||||
|
)
|
||||||
|
|
||||||
|
// means the max sdk here and any sdk value as -1 means not valid
|
||||||
|
data class Permission(
|
||||||
|
val name: String,
|
||||||
|
val sdKs: SDKs
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
@JvmInline
|
||||||
|
value class PackageName(val name: String)
|
||||||
|
|
||||||
|
fun String.toPackageName() = PackageName(this)
|
||||||
49
app/src/main/kotlin/com/looker/droidify/domain/model/Repo.kt
Normal file
49
app/src/main/kotlin/com/looker/droidify/domain/model/Repo.kt
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package com.looker.droidify.domain.model
|
||||||
|
|
||||||
|
data class Repo(
|
||||||
|
val id: Long,
|
||||||
|
val enabled: Boolean,
|
||||||
|
val address: String,
|
||||||
|
val name: String,
|
||||||
|
val description: String,
|
||||||
|
val fingerprint: Fingerprint?,
|
||||||
|
val authentication: Authentication,
|
||||||
|
val versionInfo: VersionInfo,
|
||||||
|
val mirrors: List<String>,
|
||||||
|
val antiFeatures: List<AntiFeature>,
|
||||||
|
val categories: List<Category>
|
||||||
|
) {
|
||||||
|
val shouldAuthenticate =
|
||||||
|
authentication.username.isNotEmpty() && authentication.password.isNotEmpty()
|
||||||
|
|
||||||
|
fun update(fingerprint: Fingerprint, timestamp: Long? = null, etag: String? = null): Repo {
|
||||||
|
return copy(
|
||||||
|
fingerprint = fingerprint,
|
||||||
|
versionInfo = timestamp?.let { VersionInfo(timestamp = it, etag = etag) } ?: versionInfo
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class AntiFeature(
|
||||||
|
val id: Long,
|
||||||
|
val name: String,
|
||||||
|
val icon: String = "",
|
||||||
|
val description: String = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Category(
|
||||||
|
val id: Long,
|
||||||
|
val name: String,
|
||||||
|
val icon: String = "",
|
||||||
|
val description: String = ""
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Authentication(
|
||||||
|
val username: String,
|
||||||
|
val password: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class VersionInfo(
|
||||||
|
val timestamp: Long,
|
||||||
|
val etag: String?
|
||||||
|
)
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package com.looker.droidify.graphics
|
||||||
|
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.ColorFilter
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
|
||||||
|
open class DrawableWrapper(val drawable: Drawable) : Drawable() {
|
||||||
|
init {
|
||||||
|
drawable.callback = object : Callback {
|
||||||
|
override fun invalidateDrawable(who: Drawable) {
|
||||||
|
callback?.invalidateDrawable(who)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
|
||||||
|
callback?.scheduleDrawable(who, what, `when`)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
|
||||||
|
callback?.unscheduleDrawable(who, what)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBoundsChange(bounds: Rect) {
|
||||||
|
drawable.bounds = bounds
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getIntrinsicWidth(): Int = drawable.intrinsicWidth
|
||||||
|
override fun getIntrinsicHeight(): Int = drawable.intrinsicHeight
|
||||||
|
override fun getMinimumWidth(): Int = drawable.minimumWidth
|
||||||
|
override fun getMinimumHeight(): Int = drawable.minimumHeight
|
||||||
|
|
||||||
|
override fun draw(canvas: Canvas) {
|
||||||
|
drawable.draw(canvas)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getAlpha(): Int {
|
||||||
|
return drawable.alpha
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun setAlpha(alpha: Int) {
|
||||||
|
drawable.alpha = alpha
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getColorFilter(): ColorFilter? {
|
||||||
|
return drawable.colorFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun setColorFilter(colorFilter: ColorFilter?) {
|
||||||
|
drawable.colorFilter = colorFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
override fun getOpacity(): Int = drawable.opacity
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.looker.droidify.graphics
|
||||||
|
|
||||||
|
import android.graphics.Rect
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
class PaddingDrawable(
|
||||||
|
drawable: Drawable,
|
||||||
|
private val horizontalFactor: Float,
|
||||||
|
private val aspectRatio: Float = 16f / 9f
|
||||||
|
) : DrawableWrapper(drawable) {
|
||||||
|
override fun getIntrinsicWidth(): Int =
|
||||||
|
(horizontalFactor * super.getIntrinsicWidth()).roundToInt()
|
||||||
|
|
||||||
|
override fun getIntrinsicHeight(): Int =
|
||||||
|
((horizontalFactor * aspectRatio) * super.getIntrinsicHeight()).roundToInt()
|
||||||
|
|
||||||
|
override fun onBoundsChange(bounds: Rect) {
|
||||||
|
val width = (bounds.width() / horizontalFactor).roundToInt()
|
||||||
|
val height = (bounds.height() / (horizontalFactor * aspectRatio)).roundToInt()
|
||||||
|
val left = (bounds.width() - width) / 2
|
||||||
|
val top = (bounds.height() - height) / 2
|
||||||
|
drawable.setBounds(
|
||||||
|
bounds.left + left,
|
||||||
|
bounds.top + top,
|
||||||
|
bounds.left + left + width,
|
||||||
|
bounds.top + top + height
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
118
app/src/main/kotlin/com/looker/droidify/index/IndexMerger.kt
Normal file
118
app/src/main/kotlin/com/looker/droidify/index/IndexMerger.kt
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
package com.looker.droidify.index
|
||||||
|
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.database.sqlite.SQLiteDatabase
|
||||||
|
import com.fasterxml.jackson.core.JsonToken
|
||||||
|
import com.looker.droidify.utility.common.extension.Json
|
||||||
|
import com.looker.droidify.utility.common.extension.asSequence
|
||||||
|
import com.looker.droidify.utility.common.extension.collectNotNull
|
||||||
|
import com.looker.droidify.utility.common.extension.writeDictionary
|
||||||
|
import com.looker.droidify.model.Product
|
||||||
|
import com.looker.droidify.model.Release
|
||||||
|
import com.looker.droidify.utility.serialization.product
|
||||||
|
import com.looker.droidify.utility.serialization.release
|
||||||
|
import com.looker.droidify.utility.serialization.serialize
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.Closeable
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
class IndexMerger(file: File) : Closeable {
|
||||||
|
private val db = SQLiteDatabase.openOrCreateDatabase(file, null)
|
||||||
|
|
||||||
|
init {
|
||||||
|
db.execWithResult("PRAGMA synchronous = OFF")
|
||||||
|
db.execWithResult("PRAGMA journal_mode = OFF")
|
||||||
|
db.execSQL(
|
||||||
|
"CREATE TABLE product (" +
|
||||||
|
"package_name TEXT PRIMARY KEY," +
|
||||||
|
"description TEXT NOT NULL, " +
|
||||||
|
"data BLOB NOT NULL)"
|
||||||
|
)
|
||||||
|
db.execSQL("CREATE TABLE releases (package_name TEXT PRIMARY KEY, data BLOB NOT NULL)")
|
||||||
|
db.beginTransaction()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addProducts(products: List<Product>) {
|
||||||
|
for (product in products) {
|
||||||
|
val outputStream = ByteArrayOutputStream()
|
||||||
|
Json.factory.createGenerator(outputStream)
|
||||||
|
.use { it.writeDictionary(product::serialize) }
|
||||||
|
db.insert(
|
||||||
|
"product",
|
||||||
|
null,
|
||||||
|
ContentValues().apply {
|
||||||
|
put("package_name", product.packageName)
|
||||||
|
put("description", product.description)
|
||||||
|
put("data", outputStream.toByteArray())
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addReleases(pairs: List<Pair<String, List<Release>>>) {
|
||||||
|
for (pair in pairs) {
|
||||||
|
val (packageName, releases) = pair
|
||||||
|
val outputStream = ByteArrayOutputStream()
|
||||||
|
Json.factory.createGenerator(outputStream).use {
|
||||||
|
it.writeStartArray()
|
||||||
|
for (release in releases) {
|
||||||
|
it.writeDictionary(release::serialize)
|
||||||
|
}
|
||||||
|
it.writeEndArray()
|
||||||
|
}
|
||||||
|
db.insert(
|
||||||
|
"releases",
|
||||||
|
null,
|
||||||
|
ContentValues().apply {
|
||||||
|
put("package_name", packageName)
|
||||||
|
put("data", outputStream.toByteArray())
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeTransaction() {
|
||||||
|
if (db.inTransaction()) {
|
||||||
|
db.setTransactionSuccessful()
|
||||||
|
db.endTransaction()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun forEach(repositoryId: Long, windowSize: Int, callback: (List<Product>, Int) -> Unit) {
|
||||||
|
closeTransaction()
|
||||||
|
db.rawQuery(
|
||||||
|
"""SELECT product.description, product.data AS pd, releases.data AS rd FROM product
|
||||||
|
LEFT JOIN releases ON product.package_name = releases.package_name""",
|
||||||
|
null
|
||||||
|
).use { cursor ->
|
||||||
|
cursor.asSequence().map { currentCursor ->
|
||||||
|
val description = currentCursor.getString(0)
|
||||||
|
val product = Json.factory.createParser(currentCursor.getBlob(1)).use {
|
||||||
|
it.nextToken()
|
||||||
|
it.product().apply {
|
||||||
|
this.repositoryId = repositoryId
|
||||||
|
this.description = description
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val releases = currentCursor.getBlob(2)?.let { bytes ->
|
||||||
|
Json.factory.createParser(bytes).use {
|
||||||
|
it.nextToken()
|
||||||
|
it.collectNotNull(
|
||||||
|
JsonToken.START_OBJECT
|
||||||
|
) { release() }
|
||||||
|
}
|
||||||
|
}.orEmpty()
|
||||||
|
product.copy(releases = releases)
|
||||||
|
}.windowed(windowSize, windowSize, true)
|
||||||
|
.forEach { products -> callback(products, cursor.count) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
db.use { closeTransaction() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun SQLiteDatabase.execWithResult(sql: String) {
|
||||||
|
rawQuery(sql, null).use { it.count }
|
||||||
|
}
|
||||||
|
}
|
||||||
559
app/src/main/kotlin/com/looker/droidify/index/IndexV1Parser.kt
Normal file
559
app/src/main/kotlin/com/looker/droidify/index/IndexV1Parser.kt
Normal file
@@ -0,0 +1,559 @@
|
|||||||
|
package com.looker.droidify.index
|
||||||
|
|
||||||
|
import android.content.res.Resources
|
||||||
|
import androidx.core.os.ConfigurationCompat.getLocales
|
||||||
|
import androidx.core.os.LocaleListCompat
|
||||||
|
import com.fasterxml.jackson.core.JsonParser
|
||||||
|
import com.fasterxml.jackson.core.JsonToken
|
||||||
|
import com.looker.droidify.utility.common.extension.Json
|
||||||
|
import com.looker.droidify.utility.common.extension.collectDistinctNotEmptyStrings
|
||||||
|
import com.looker.droidify.utility.common.extension.collectNotNull
|
||||||
|
import com.looker.droidify.utility.common.extension.forEach
|
||||||
|
import com.looker.droidify.utility.common.extension.forEachKey
|
||||||
|
import com.looker.droidify.utility.common.extension.illegal
|
||||||
|
import com.looker.droidify.model.Product
|
||||||
|
import com.looker.droidify.model.Product.Donate.Bitcoin
|
||||||
|
import com.looker.droidify.model.Product.Donate.Liberapay
|
||||||
|
import com.looker.droidify.model.Product.Donate.Litecoin
|
||||||
|
import com.looker.droidify.model.Product.Donate.OpenCollective
|
||||||
|
import com.looker.droidify.model.Product.Donate.Regular
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.LARGE_TABLET
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.PHONE
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.SMALL_TABLET
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.TV
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.VIDEO
|
||||||
|
import com.looker.droidify.model.Product.Screenshot.Type.WEAR
|
||||||
|
import com.looker.droidify.model.Release
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.nullIfEmpty
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
object IndexV1Parser {
|
||||||
|
interface Callback {
|
||||||
|
fun onRepository(
|
||||||
|
mirrors: List<String>,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
version: Int,
|
||||||
|
timestamp: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
fun onProduct(product: Product)
|
||||||
|
fun onReleases(packageName: String, releases: List<Release>)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Screenshots(
|
||||||
|
val video: List<String>,
|
||||||
|
val phone: List<String>,
|
||||||
|
val smallTablet: List<String>,
|
||||||
|
val largeTablet: List<String>,
|
||||||
|
val wear: List<String>,
|
||||||
|
val tv: List<String>,
|
||||||
|
)
|
||||||
|
|
||||||
|
private class Localized(
|
||||||
|
val name: String,
|
||||||
|
val summary: String,
|
||||||
|
val description: String,
|
||||||
|
val whatsNew: String,
|
||||||
|
val metadataIcon: String,
|
||||||
|
val screenshots: Screenshots?
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun <T> Map<String, Localized>.getAndCall(
|
||||||
|
key: String,
|
||||||
|
callback: (String, Localized) -> T?
|
||||||
|
): T? {
|
||||||
|
return this[key]?.let { callback(key, it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the best localization for the given [localeList]
|
||||||
|
* from collections.
|
||||||
|
*/
|
||||||
|
private fun <T> Map<String, T>?.getBestLocale(localeList: LocaleListCompat): T? {
|
||||||
|
if (isNullOrEmpty()) return null
|
||||||
|
val firstMatch = localeList.getFirstMatch(keys.toTypedArray()) ?: return null
|
||||||
|
val tag = firstMatch.toLanguageTag()
|
||||||
|
// try first matched tag first (usually has region tag, e.g. de-DE)
|
||||||
|
return get(tag) ?: run {
|
||||||
|
// split away stuff like script and try language and region only
|
||||||
|
val langCountryTag = "${firstMatch.language}-${firstMatch.country}"
|
||||||
|
getOrStartsWith(langCountryTag) ?: run {
|
||||||
|
// split away region tag and try language only
|
||||||
|
val langTag = firstMatch.language
|
||||||
|
// try language, then English and then just take the first of the list
|
||||||
|
getOrStartsWith(langTag) ?: get("en-US") ?: get("en") ?: values.first()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the value from the map with the given key or if that key is not contained in the map,
|
||||||
|
* tries the first map key that starts with the given key.
|
||||||
|
* If nothing matches, null is returned.
|
||||||
|
*
|
||||||
|
* This is useful when looking for a language tag like `fr_CH` and falling back to `fr`
|
||||||
|
* in a map that has `fr_FR` as a key.
|
||||||
|
*/
|
||||||
|
private fun <T> Map<String, T>.getOrStartsWith(s: String): T? = get(s) ?: run {
|
||||||
|
entries.forEach { (key, value) ->
|
||||||
|
if (key.startsWith(s)) return value
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> Map<String, Localized>.find(callback: (String, Localized) -> T?): T? {
|
||||||
|
return getAndCall("en-US", callback)
|
||||||
|
?: getAndCall("en_US", callback)
|
||||||
|
?: getAndCall("en", callback)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> Map<String, Localized>.findLocalized(callback: (Localized) -> T?): T? {
|
||||||
|
return getBestLocale(getLocales(Resources.getSystem().configuration))?.let { callback(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Map<String, Localized>.findString(
|
||||||
|
fallback: String,
|
||||||
|
callback: (Localized) -> String
|
||||||
|
): String {
|
||||||
|
return (find { _, localized -> callback(localized).nullIfEmpty() } ?: fallback).trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Map<String, Localized>.findLocalizedString(
|
||||||
|
fallback: String,
|
||||||
|
callback: (Localized) -> String
|
||||||
|
): String {
|
||||||
|
// @BLumia: it's possible a key of a certain Localized object is empty, so we still need a fallback
|
||||||
|
return (
|
||||||
|
findLocalized { localized -> callback(localized).trim().nullIfEmpty() } ?: findString(
|
||||||
|
fallback,
|
||||||
|
callback
|
||||||
|
)
|
||||||
|
).trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
internal object DonateComparator : Comparator<Product.Donate> {
|
||||||
|
private val classes = listOf(
|
||||||
|
Regular::class,
|
||||||
|
Bitcoin::class,
|
||||||
|
Litecoin::class,
|
||||||
|
Liberapay::class,
|
||||||
|
OpenCollective::class
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun compare(donate1: Product.Donate, donate2: Product.Donate): Int {
|
||||||
|
val index1 = classes.indexOf(donate1::class)
|
||||||
|
val index2 = classes.indexOf(donate2::class)
|
||||||
|
return when {
|
||||||
|
index1 >= 0 && index2 == -1 -> -1
|
||||||
|
index2 >= 0 && index1 == -1 -> 1
|
||||||
|
else -> index1.compareTo(index2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val DICT_REPO = "repo"
|
||||||
|
private const val DICT_PRODUCT = "apps"
|
||||||
|
private const val DICT_RELEASE = "packages"
|
||||||
|
|
||||||
|
private const val KEY_REPO_ADDRESS = "address"
|
||||||
|
private const val KEY_REPO_MIRRORS = "mirrors"
|
||||||
|
private const val KEY_REPO_NAME = "name"
|
||||||
|
private const val KEY_REPO_DESC = "description"
|
||||||
|
private const val KEY_REPO_VER = "version"
|
||||||
|
private const val KEY_REPO_TIME = "timestamp"
|
||||||
|
|
||||||
|
fun parse(repositoryId: Long, inputStream: InputStream, callback: Callback) {
|
||||||
|
val jsonParser = Json.factory.createParser(inputStream)
|
||||||
|
if (jsonParser.nextToken() != JsonToken.START_OBJECT) {
|
||||||
|
jsonParser.illegal()
|
||||||
|
} else {
|
||||||
|
jsonParser.forEachKey { key ->
|
||||||
|
when {
|
||||||
|
key.dictionary(DICT_REPO) -> {
|
||||||
|
var address = ""
|
||||||
|
var mirrors = emptyList<String>()
|
||||||
|
var name = ""
|
||||||
|
var description = ""
|
||||||
|
var version = 0
|
||||||
|
var timestamp = 0L
|
||||||
|
forEachKey {
|
||||||
|
when {
|
||||||
|
it.string(KEY_REPO_ADDRESS) -> address = valueAsString
|
||||||
|
it.array(KEY_REPO_MIRRORS) -> mirrors =
|
||||||
|
collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
it.string(KEY_REPO_NAME) -> name = valueAsString
|
||||||
|
it.string(KEY_REPO_DESC) -> description = valueAsString
|
||||||
|
it.number(KEY_REPO_VER) -> version = valueAsInt
|
||||||
|
it.number(KEY_REPO_TIME) -> timestamp = valueAsLong
|
||||||
|
else -> skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val realMirrors = (
|
||||||
|
if (address.isNotEmpty()) {
|
||||||
|
listOf(address)
|
||||||
|
} else {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
) + mirrors
|
||||||
|
callback.onRepository(
|
||||||
|
mirrors = realMirrors.distinct(),
|
||||||
|
name = name,
|
||||||
|
description = description,
|
||||||
|
version = version,
|
||||||
|
timestamp = timestamp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
key.array(DICT_PRODUCT) -> forEach(JsonToken.START_OBJECT) {
|
||||||
|
val product = parseProduct(repositoryId)
|
||||||
|
callback.onProduct(product)
|
||||||
|
}
|
||||||
|
|
||||||
|
key.dictionary(DICT_RELEASE) -> forEachKey {
|
||||||
|
if (it.token == JsonToken.START_ARRAY) {
|
||||||
|
val packageName = it.key
|
||||||
|
val releases = collectNotNull(JsonToken.START_OBJECT) { parseRelease() }
|
||||||
|
callback.onReleases(packageName, releases)
|
||||||
|
} else {
|
||||||
|
skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val KEY_PRODUCT_PACKAGENAME = "packageName"
|
||||||
|
private const val KEY_PRODUCT_NAME = "name"
|
||||||
|
private const val KEY_PRODUCT_SUMMARY = "summary"
|
||||||
|
private const val KEY_PRODUCT_DESCRIPTION = "description"
|
||||||
|
private const val KEY_PRODUCT_ICON = "icon"
|
||||||
|
private const val KEY_PRODUCT_AUTHORNAME = "authorName"
|
||||||
|
private const val KEY_PRODUCT_AUTHOREMAIL = "authorEmail"
|
||||||
|
private const val KEY_PRODUCT_AUTHORWEBSITE = "authorWebSite"
|
||||||
|
private const val KEY_PRODUCT_SOURCECODE = "sourceCode"
|
||||||
|
private const val KEY_PRODUCT_CHANGELOG = "changelog"
|
||||||
|
private const val KEY_PRODUCT_WEBSITE = "webSite"
|
||||||
|
private const val KEY_PRODUCT_ISSUETRACKER = "issueTracker"
|
||||||
|
private const val KEY_PRODUCT_ADDED = "added"
|
||||||
|
private const val KEY_PRODUCT_LASTUPDATED = "lastUpdated"
|
||||||
|
private const val KEY_PRODUCT_SUGGESTEDVERSIONCODE = "suggestedVersionCode"
|
||||||
|
private const val KEY_PRODUCT_CATEGORIES = "categories"
|
||||||
|
private const val KEY_PRODUCT_ANTIFEATURES = "antiFeatures"
|
||||||
|
private const val KEY_PRODUCT_LICENSE = "license"
|
||||||
|
private const val KEY_PRODUCT_DONATE = "donate"
|
||||||
|
private const val KEY_PRODUCT_BITCOIN = "bitcoin"
|
||||||
|
private const val KEY_PRODUCT_LIBERAPAYID = "liberapay"
|
||||||
|
private const val KEY_PRODUCT_LITECOIN = "litecoin"
|
||||||
|
private const val KEY_PRODUCT_OPENCOLLECTIVE = "openCollective"
|
||||||
|
private const val KEY_PRODUCT_LOCALIZED = "localized"
|
||||||
|
private const val KEY_PRODUCT_WHATSNEW = "whatsNew"
|
||||||
|
private const val KEY_PRODUCT_PHONE_SCREENSHOTS = "phoneScreenshots"
|
||||||
|
private const val KEY_PRODUCT_SEVEN_INCH_SCREENSHOTS = "sevenInchScreenshots"
|
||||||
|
private const val KEY_PRODUCT_TEN_INCH_SCREENSHOTS = "tenInchScreenshots"
|
||||||
|
private const val KEY_PRODUCT_WEAR_SCREENSHOTS = "wearScreenshots"
|
||||||
|
private const val KEY_PRODUCT_TV_SCREENSHOTS = "tvScreenshots"
|
||||||
|
private const val KEY_PRODUCT_VIDEO = "video"
|
||||||
|
|
||||||
|
private fun JsonParser.parseProduct(repositoryId: Long): Product {
|
||||||
|
var packageName = ""
|
||||||
|
var nameFallback = ""
|
||||||
|
var summaryFallback = ""
|
||||||
|
var descriptionFallback = ""
|
||||||
|
var icon = ""
|
||||||
|
var authorName = ""
|
||||||
|
var authorEmail = ""
|
||||||
|
var authorWeb = ""
|
||||||
|
var source = ""
|
||||||
|
var changelog = ""
|
||||||
|
var web = ""
|
||||||
|
var tracker = ""
|
||||||
|
var added = 0L
|
||||||
|
var updated = 0L
|
||||||
|
var suggestedVersionCode = 0L
|
||||||
|
var categories = emptyList<String>()
|
||||||
|
var antiFeatures = emptyList<String>()
|
||||||
|
val licenses = mutableListOf<String>()
|
||||||
|
val donates = mutableListOf<Product.Donate>()
|
||||||
|
val localizedMap = mutableMapOf<String, Localized>()
|
||||||
|
forEachKey { key ->
|
||||||
|
when {
|
||||||
|
key.string(KEY_PRODUCT_PACKAGENAME) -> packageName = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_NAME) -> nameFallback = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_SUMMARY) -> summaryFallback = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_DESCRIPTION) -> descriptionFallback = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_ICON) -> icon = validateIcon(valueAsString)
|
||||||
|
key.string(KEY_PRODUCT_AUTHORNAME) -> authorName = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_AUTHOREMAIL) -> authorEmail = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_AUTHORWEBSITE) -> authorWeb = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_SOURCECODE) -> source = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_CHANGELOG) -> changelog = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_WEBSITE) -> web = valueAsString
|
||||||
|
key.string(KEY_PRODUCT_ISSUETRACKER) -> tracker = valueAsString
|
||||||
|
key.number(KEY_PRODUCT_ADDED) -> added = valueAsLong
|
||||||
|
key.number(KEY_PRODUCT_LASTUPDATED) -> updated = valueAsLong
|
||||||
|
key.string(KEY_PRODUCT_SUGGESTEDVERSIONCODE) ->
|
||||||
|
suggestedVersionCode =
|
||||||
|
valueAsString.toLongOrNull() ?: 0L
|
||||||
|
|
||||||
|
key.array(KEY_PRODUCT_CATEGORIES) -> categories = collectDistinctNotEmptyStrings()
|
||||||
|
key.array(KEY_PRODUCT_ANTIFEATURES) -> antiFeatures =
|
||||||
|
collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
key.string(KEY_PRODUCT_LICENSE) -> licenses += valueAsString.split(',')
|
||||||
|
.filter { it.isNotEmpty() }
|
||||||
|
|
||||||
|
key.string(KEY_PRODUCT_DONATE) -> donates += Regular(valueAsString)
|
||||||
|
key.string(KEY_PRODUCT_BITCOIN) -> donates += Bitcoin(valueAsString)
|
||||||
|
key.string(KEY_PRODUCT_LIBERAPAYID) -> donates += Liberapay(valueAsString)
|
||||||
|
key.string(KEY_PRODUCT_LITECOIN) -> donates += Litecoin(valueAsString)
|
||||||
|
key.string(KEY_PRODUCT_OPENCOLLECTIVE) -> donates += OpenCollective(valueAsString)
|
||||||
|
|
||||||
|
key.dictionary(KEY_PRODUCT_LOCALIZED) -> forEachKey { localizedKey ->
|
||||||
|
if (localizedKey.token == JsonToken.START_OBJECT) {
|
||||||
|
val locale = localizedKey.key
|
||||||
|
var name = ""
|
||||||
|
var summary = ""
|
||||||
|
var description = ""
|
||||||
|
var whatsNew = ""
|
||||||
|
var metadataIcon = ""
|
||||||
|
var phone = emptyList<String>()
|
||||||
|
var smallTablet = emptyList<String>()
|
||||||
|
var largeTablet = emptyList<String>()
|
||||||
|
var wear = emptyList<String>()
|
||||||
|
var tv = emptyList<String>()
|
||||||
|
var video = emptyList<String>()
|
||||||
|
forEachKey {
|
||||||
|
when {
|
||||||
|
it.string(KEY_PRODUCT_NAME) -> name = valueAsString
|
||||||
|
it.string(KEY_PRODUCT_SUMMARY) -> summary = valueAsString
|
||||||
|
it.string(KEY_PRODUCT_DESCRIPTION) -> description = valueAsString
|
||||||
|
it.string(KEY_PRODUCT_WHATSNEW) -> whatsNew = valueAsString
|
||||||
|
it.string(KEY_PRODUCT_ICON) -> metadataIcon = valueAsString
|
||||||
|
it.string(KEY_PRODUCT_VIDEO) -> video = listOf(valueAsString)
|
||||||
|
it.array(KEY_PRODUCT_PHONE_SCREENSHOTS) ->
|
||||||
|
phone = collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
it.array(KEY_PRODUCT_SEVEN_INCH_SCREENSHOTS) ->
|
||||||
|
smallTablet = collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
it.array(KEY_PRODUCT_TEN_INCH_SCREENSHOTS) ->
|
||||||
|
largeTablet = collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
it.array(KEY_PRODUCT_WEAR_SCREENSHOTS) ->
|
||||||
|
wear = collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
it.array(KEY_PRODUCT_TV_SCREENSHOTS) ->
|
||||||
|
tv = collectDistinctNotEmptyStrings()
|
||||||
|
|
||||||
|
else -> skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val isScreenshotEmpty =
|
||||||
|
arrayOf(video, phone, smallTablet, largeTablet, wear, tv)
|
||||||
|
.any { it.isNotEmpty() }
|
||||||
|
val screenshots =
|
||||||
|
if (isScreenshotEmpty) {
|
||||||
|
Screenshots(video, phone, smallTablet, largeTablet, wear, tv)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
localizedMap[locale] = Localized(
|
||||||
|
name = name,
|
||||||
|
summary = summary,
|
||||||
|
description = description,
|
||||||
|
whatsNew = whatsNew,
|
||||||
|
metadataIcon = metadataIcon.nullIfEmpty()?.let { "$locale/$it" }
|
||||||
|
.orEmpty(),
|
||||||
|
screenshots = screenshots,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val name = localizedMap.findLocalizedString(nameFallback) { it.name }
|
||||||
|
val summary = localizedMap.findLocalizedString(summaryFallback) { it.summary }
|
||||||
|
val description =
|
||||||
|
localizedMap.findLocalizedString(descriptionFallback) { it.description }.replace(
|
||||||
|
"\n",
|
||||||
|
"<br/>"
|
||||||
|
)
|
||||||
|
val whatsNew = localizedMap.findLocalizedString("") { it.whatsNew }.replace("\n", "<br/>")
|
||||||
|
val metadataIcon = localizedMap.findLocalizedString("") { it.metadataIcon }.ifEmpty {
|
||||||
|
localizedMap.firstNotNullOfOrNull { it.value.metadataIcon }.orEmpty()
|
||||||
|
}
|
||||||
|
val screenshotPairs =
|
||||||
|
localizedMap.find { key, localized -> localized.screenshots?.let { Pair(key, it) } }
|
||||||
|
val screenshots = screenshotPairs?.let { (key, screenshots) ->
|
||||||
|
screenshots.video.map { Product.Screenshot(key, VIDEO, it) } +
|
||||||
|
screenshots.phone.map { Product.Screenshot(key, PHONE, it) } +
|
||||||
|
screenshots.smallTablet.map { Product.Screenshot(key, SMALL_TABLET, it) } +
|
||||||
|
screenshots.largeTablet.map { Product.Screenshot(key, LARGE_TABLET, it) } +
|
||||||
|
screenshots.wear.map { Product.Screenshot(key, WEAR, it) } +
|
||||||
|
screenshots.tv.map { Product.Screenshot(key, TV, it) }
|
||||||
|
}.orEmpty()
|
||||||
|
return Product(
|
||||||
|
repositoryId = repositoryId,
|
||||||
|
packageName = packageName,
|
||||||
|
name = name,
|
||||||
|
summary = summary,
|
||||||
|
description = description,
|
||||||
|
whatsNew = whatsNew,
|
||||||
|
icon = icon,
|
||||||
|
metadataIcon = metadataIcon,
|
||||||
|
author = Product.Author(authorName, authorEmail, authorWeb),
|
||||||
|
source = source,
|
||||||
|
changelog = changelog,
|
||||||
|
web = web,
|
||||||
|
tracker = tracker,
|
||||||
|
added = added,
|
||||||
|
updated = updated,
|
||||||
|
suggestedVersionCode = suggestedVersionCode,
|
||||||
|
categories = categories,
|
||||||
|
antiFeatures = antiFeatures,
|
||||||
|
licenses = licenses,
|
||||||
|
donates = donates.sortedWith(DonateComparator),
|
||||||
|
screenshots = screenshots,
|
||||||
|
releases = emptyList()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val KEY_RELEASE_VERSIONNAME = "versionName"
|
||||||
|
private const val KEY_RELEASE_VERSIONCODE = "versionCode"
|
||||||
|
private const val KEY_RELEASE_ADDED = "added"
|
||||||
|
private const val KEY_RELEASE_SIZE = "size"
|
||||||
|
private const val KEY_RELEASE_MINSDKVERSION = "minSdkVersion"
|
||||||
|
private const val KEY_RELEASE_TARGETSDKVERSION = "targetSdkVersion"
|
||||||
|
private const val KEY_RELEASE_MAXSDKVERSION = "maxSdkVersion"
|
||||||
|
private const val KEY_RELEASE_SRCNAME = "srcname"
|
||||||
|
private const val KEY_RELEASE_APKNAME = "apkName"
|
||||||
|
private const val KEY_RELEASE_HASH = "hash"
|
||||||
|
private const val KEY_RELEASE_HASHTYPE = "hashType"
|
||||||
|
private const val KEY_RELEASE_SIG = "sig"
|
||||||
|
private const val KEY_RELEASE_OBBMAINFILE = "obbMainFile"
|
||||||
|
private const val KEY_RELEASE_OBBMAINFILESHA256 = "obbMainFileSha256"
|
||||||
|
private const val KEY_RELEASE_OBBPATCHFILE = "obbPatchFile"
|
||||||
|
private const val KEY_RELEASE_OBBPATCHFILESHA256 = "obbPatchFileSha256"
|
||||||
|
private const val KEY_RELEASE_USESPERMISSION = "uses-permission"
|
||||||
|
private const val KEY_RELEASE_USESPERMISSIONSDK23 = "uses-permission-sdk-23"
|
||||||
|
private const val KEY_RELEASE_FEATURES = "features"
|
||||||
|
private const val KEY_RELEASE_NATIVECODE = "nativecode"
|
||||||
|
|
||||||
|
private fun JsonParser.parseRelease(): Release {
|
||||||
|
var version = ""
|
||||||
|
var versionCode = 0L
|
||||||
|
var added = 0L
|
||||||
|
var size = 0L
|
||||||
|
var minSdkVersion = 0
|
||||||
|
var targetSdkVersion = 0
|
||||||
|
var maxSdkVersion = 0
|
||||||
|
var source = ""
|
||||||
|
var release = ""
|
||||||
|
var hash = ""
|
||||||
|
var hashTypeCandidate = ""
|
||||||
|
var signature = ""
|
||||||
|
var obbMain = ""
|
||||||
|
var obbMainHash = ""
|
||||||
|
var obbPatch = ""
|
||||||
|
var obbPatchHash = ""
|
||||||
|
val permissions = linkedSetOf<String>()
|
||||||
|
var features = emptyList<String>()
|
||||||
|
var platforms = emptyList<String>()
|
||||||
|
forEachKey { key ->
|
||||||
|
when {
|
||||||
|
key.string(KEY_RELEASE_VERSIONNAME) -> version = valueAsString
|
||||||
|
key.number(KEY_RELEASE_VERSIONCODE) -> versionCode = valueAsLong
|
||||||
|
key.number(KEY_RELEASE_ADDED) -> added = valueAsLong
|
||||||
|
key.number(KEY_RELEASE_SIZE) -> size = valueAsLong
|
||||||
|
key.number(KEY_RELEASE_MINSDKVERSION) -> minSdkVersion = valueAsInt
|
||||||
|
key.number(KEY_RELEASE_TARGETSDKVERSION) -> targetSdkVersion = valueAsInt
|
||||||
|
key.number(KEY_RELEASE_MAXSDKVERSION) -> maxSdkVersion = valueAsInt
|
||||||
|
key.string(KEY_RELEASE_SRCNAME) -> source = valueAsString
|
||||||
|
key.string(KEY_RELEASE_APKNAME) -> release = valueAsString
|
||||||
|
key.string(KEY_RELEASE_HASH) -> hash = valueAsString
|
||||||
|
key.string(KEY_RELEASE_HASHTYPE) -> hashTypeCandidate = valueAsString
|
||||||
|
key.string(KEY_RELEASE_SIG) -> signature = valueAsString
|
||||||
|
key.string(KEY_RELEASE_OBBMAINFILE) -> obbMain = valueAsString
|
||||||
|
key.string(KEY_RELEASE_OBBMAINFILESHA256) -> obbMainHash = valueAsString
|
||||||
|
key.string(KEY_RELEASE_OBBPATCHFILE) -> obbPatch = valueAsString
|
||||||
|
key.string(KEY_RELEASE_OBBPATCHFILESHA256) -> obbPatchHash = valueAsString
|
||||||
|
key.array(KEY_RELEASE_USESPERMISSION) -> collectPermissions(permissions, 0)
|
||||||
|
key.array(KEY_RELEASE_USESPERMISSIONSDK23) -> collectPermissions(permissions, 23)
|
||||||
|
key.array(KEY_RELEASE_FEATURES) -> features = collectDistinctNotEmptyStrings()
|
||||||
|
key.array(KEY_RELEASE_NATIVECODE) -> platforms = collectDistinctNotEmptyStrings()
|
||||||
|
else -> skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val hashType =
|
||||||
|
if (hash.isNotEmpty() && hashTypeCandidate.isEmpty()) "sha256" else hashTypeCandidate
|
||||||
|
val obbMainHashType = if (obbMainHash.isNotEmpty()) "sha256" else ""
|
||||||
|
val obbPatchHashType = if (obbPatchHash.isNotEmpty()) "sha256" else ""
|
||||||
|
return Release(
|
||||||
|
selected = false,
|
||||||
|
version = version,
|
||||||
|
versionCode = versionCode,
|
||||||
|
added = added,
|
||||||
|
size = size,
|
||||||
|
minSdkVersion = minSdkVersion,
|
||||||
|
targetSdkVersion = targetSdkVersion,
|
||||||
|
maxSdkVersion = maxSdkVersion,
|
||||||
|
source = source,
|
||||||
|
release = release,
|
||||||
|
hash = hash,
|
||||||
|
hashType = hashType,
|
||||||
|
signature = signature,
|
||||||
|
obbMain = obbMain,
|
||||||
|
obbMainHash = obbMainHash,
|
||||||
|
obbMainHashType = obbMainHashType,
|
||||||
|
obbPatch = obbPatch,
|
||||||
|
obbPatchHash = obbPatchHash,
|
||||||
|
obbPatchHashType = obbPatchHashType,
|
||||||
|
permissions = permissions.toList(),
|
||||||
|
features = features,
|
||||||
|
platforms = platforms,
|
||||||
|
incompatibilities = emptyList()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JsonParser.collectPermissions(permissions: LinkedHashSet<String>, minSdk: Int) {
|
||||||
|
forEach(JsonToken.START_ARRAY) {
|
||||||
|
val firstToken = nextToken()
|
||||||
|
val permission = if (firstToken == JsonToken.VALUE_STRING) valueAsString else ""
|
||||||
|
if (firstToken != JsonToken.END_ARRAY) {
|
||||||
|
val secondToken = nextToken()
|
||||||
|
val maxSdk = if (secondToken == JsonToken.VALUE_NUMBER_INT) valueAsInt else 0
|
||||||
|
if (permission.isNotEmpty() &&
|
||||||
|
SdkCheck.sdk >= minSdk && (
|
||||||
|
maxSdk <= 0 ||
|
||||||
|
SdkCheck.sdk <= maxSdk
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
permissions.add(permission)
|
||||||
|
}
|
||||||
|
if (secondToken != JsonToken.END_ARRAY) {
|
||||||
|
while (true) {
|
||||||
|
val token = nextToken()
|
||||||
|
if (token == JsonToken.END_ARRAY) {
|
||||||
|
break
|
||||||
|
} else if (token.isStructStart) {
|
||||||
|
skipChildren()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateIcon(icon: String): String {
|
||||||
|
return if (icon.endsWith(".xml")) "" else icon
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,461 @@
|
|||||||
|
package com.looker.droidify.index
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import com.looker.droidify.database.Database
|
||||||
|
import com.looker.droidify.domain.model.fingerprint
|
||||||
|
import com.looker.droidify.model.Product
|
||||||
|
import com.looker.droidify.model.Release
|
||||||
|
import com.looker.droidify.model.Repository
|
||||||
|
import com.looker.droidify.network.Downloader
|
||||||
|
import com.looker.droidify.network.NetworkResponse
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.extension.toFormattedString
|
||||||
|
import com.looker.droidify.utility.common.result.Result
|
||||||
|
import com.looker.droidify.utility.extension.android.Android
|
||||||
|
import com.looker.droidify.utility.getProgress
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.filter
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import java.io.File
|
||||||
|
import java.security.CodeSigner
|
||||||
|
import java.security.cert.Certificate
|
||||||
|
import java.util.jar.JarEntry
|
||||||
|
import java.util.jar.JarFile
|
||||||
|
|
||||||
|
object RepositoryUpdater {
|
||||||
|
enum class Stage {
|
||||||
|
DOWNLOAD, PROCESS, MERGE, COMMIT
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO Add support for Index-V2 and also cleanup everything here
|
||||||
|
enum class IndexType(
|
||||||
|
val jarName: String,
|
||||||
|
val contentName: String
|
||||||
|
) {
|
||||||
|
INDEX_V1("index-v1.jar", "index-v1.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class ErrorType {
|
||||||
|
NETWORK, HTTP, VALIDATION, PARSING
|
||||||
|
}
|
||||||
|
|
||||||
|
class UpdateException : Exception {
|
||||||
|
val errorType: ErrorType
|
||||||
|
|
||||||
|
constructor(errorType: ErrorType, message: String) : super(message) {
|
||||||
|
this.errorType = errorType
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(errorType: ErrorType, message: String, cause: Exception) : super(
|
||||||
|
message,
|
||||||
|
cause
|
||||||
|
) {
|
||||||
|
this.errorType = errorType
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val updaterLock = Any()
|
||||||
|
private val cleanupLock = Any()
|
||||||
|
|
||||||
|
private lateinit var downloader: Downloader
|
||||||
|
|
||||||
|
fun init(scope: CoroutineScope, downloader: Downloader) {
|
||||||
|
this.downloader = downloader
|
||||||
|
scope.launch {
|
||||||
|
// No need of mutex because it is in same coroutine scope
|
||||||
|
var lastDisabled = emptyMap<Long, Boolean>()
|
||||||
|
Database.RepositoryAdapter
|
||||||
|
.getAllRemovedStream()
|
||||||
|
.map { deletedRepos ->
|
||||||
|
deletedRepos
|
||||||
|
.filterNot { it.key in lastDisabled.keys }
|
||||||
|
.also { lastDisabled = deletedRepos }
|
||||||
|
}
|
||||||
|
// To not perform complete cleanup on startup
|
||||||
|
.drop(1)
|
||||||
|
.filter { it.isNotEmpty() }
|
||||||
|
.collect(Database.RepositoryAdapter::cleanup)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun await() {
|
||||||
|
synchronized(updaterLock) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun update(
|
||||||
|
context: Context,
|
||||||
|
repository: Repository,
|
||||||
|
unstable: Boolean,
|
||||||
|
callback: (Stage, Long, Long?) -> Unit
|
||||||
|
) = update(
|
||||||
|
context = context,
|
||||||
|
repository = repository,
|
||||||
|
unstable = unstable,
|
||||||
|
indexTypes = listOf(IndexType.INDEX_V1),
|
||||||
|
callback = callback
|
||||||
|
)
|
||||||
|
|
||||||
|
private suspend fun update(
|
||||||
|
context: Context,
|
||||||
|
repository: Repository,
|
||||||
|
unstable: Boolean,
|
||||||
|
indexTypes: List<IndexType>,
|
||||||
|
callback: (Stage, Long, Long?) -> Unit
|
||||||
|
): Result<Boolean> = withContext(Dispatchers.IO) {
|
||||||
|
val indexType = indexTypes[0]
|
||||||
|
when (val request = downloadIndex(context, repository, indexType, callback)) {
|
||||||
|
is Result.Error -> {
|
||||||
|
val result = request.data
|
||||||
|
?: return@withContext Result.Error(request.exception, false)
|
||||||
|
|
||||||
|
val file = request.data?.file
|
||||||
|
?: return@withContext Result.Error(request.exception, false)
|
||||||
|
file.delete()
|
||||||
|
if (result.statusCode == 404 && indexTypes.isNotEmpty()) {
|
||||||
|
update(
|
||||||
|
context = context,
|
||||||
|
repository = repository,
|
||||||
|
indexTypes = indexTypes.subList(1, indexTypes.size),
|
||||||
|
unstable = unstable,
|
||||||
|
callback = callback
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Result.Error(
|
||||||
|
UpdateException(
|
||||||
|
ErrorType.HTTP,
|
||||||
|
"Invalid response: HTTP ${result.statusCode}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Result.Success -> {
|
||||||
|
if (request.data.isUnmodified) {
|
||||||
|
request.data.file.delete()
|
||||||
|
Result.Success(false)
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
val isFileParsedSuccessfully = processFile(
|
||||||
|
context = context,
|
||||||
|
repository = repository,
|
||||||
|
indexType = indexType,
|
||||||
|
unstable = unstable,
|
||||||
|
file = request.data.file,
|
||||||
|
lastModified = request.data.lastModified,
|
||||||
|
entityTag = request.data.entityTag,
|
||||||
|
callback = callback
|
||||||
|
)
|
||||||
|
Result.Success(isFileParsedSuccessfully)
|
||||||
|
} catch (e: UpdateException) {
|
||||||
|
Result.Error(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun downloadIndex(
|
||||||
|
context: Context,
|
||||||
|
repository: Repository,
|
||||||
|
indexType: IndexType,
|
||||||
|
callback: (Stage, Long, Long?) -> Unit
|
||||||
|
): Result<IndexFile> = withContext(Dispatchers.IO) {
|
||||||
|
val file = Cache.getTemporaryFile(context)
|
||||||
|
val result = downloader.downloadToFile(
|
||||||
|
url = Uri.parse(repository.address).buildUpon()
|
||||||
|
.appendPath(indexType.jarName).build().toString(),
|
||||||
|
target = file,
|
||||||
|
headers = {
|
||||||
|
ifModifiedSince(repository.lastModified)
|
||||||
|
etag(repository.entityTag)
|
||||||
|
authentication(repository.authentication)
|
||||||
|
}
|
||||||
|
) { read, total ->
|
||||||
|
callback(Stage.DOWNLOAD, read.value, total.value.takeIf { it != 0L })
|
||||||
|
}
|
||||||
|
|
||||||
|
when (result) {
|
||||||
|
is NetworkResponse.Success -> {
|
||||||
|
Result.Success(
|
||||||
|
IndexFile(
|
||||||
|
isUnmodified = result.statusCode == 304,
|
||||||
|
lastModified = result.lastModified?.toFormattedString() ?: "",
|
||||||
|
entityTag = result.etag ?: "",
|
||||||
|
statusCode = result.statusCode,
|
||||||
|
file = file
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkResponse.Error -> {
|
||||||
|
file.delete()
|
||||||
|
when (result) {
|
||||||
|
is NetworkResponse.Error.Http -> {
|
||||||
|
val errorType = if (result.statusCode in 400..499) {
|
||||||
|
ErrorType.HTTP
|
||||||
|
} else {
|
||||||
|
ErrorType.NETWORK
|
||||||
|
}
|
||||||
|
|
||||||
|
Result.Error(
|
||||||
|
UpdateException(
|
||||||
|
errorType = errorType,
|
||||||
|
message = "Failed with Status: ${result.statusCode}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkResponse.Error.ConnectionTimeout -> Result.Error(result.exception)
|
||||||
|
is NetworkResponse.Error.IO -> Result.Error(result.exception)
|
||||||
|
is NetworkResponse.Error.SocketTimeout -> Result.Error(result.exception)
|
||||||
|
is NetworkResponse.Error.Unknown -> Result.Error(result.exception)
|
||||||
|
// TODO: Add Validator
|
||||||
|
is NetworkResponse.Error.Validation -> Result.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun processFile(
|
||||||
|
context: Context,
|
||||||
|
repository: Repository,
|
||||||
|
indexType: IndexType,
|
||||||
|
unstable: Boolean,
|
||||||
|
file: File,
|
||||||
|
mergerFile: File = Cache.getTemporaryFile(context),
|
||||||
|
lastModified: String,
|
||||||
|
entityTag: String,
|
||||||
|
callback: (Stage, Long, Long?) -> Unit
|
||||||
|
): Boolean {
|
||||||
|
var rollback = true
|
||||||
|
return synchronized(updaterLock) {
|
||||||
|
try {
|
||||||
|
val jarFile = JarFile(file, true)
|
||||||
|
val indexEntry = jarFile.getEntry(indexType.contentName) as JarEntry
|
||||||
|
val total = indexEntry.size
|
||||||
|
Database.UpdaterAdapter.createTemporaryTable()
|
||||||
|
val features = context.packageManager.systemAvailableFeatures
|
||||||
|
.asSequence().map { it.name }.toSet() + setOf("android.hardware.touchscreen")
|
||||||
|
|
||||||
|
var changedRepository: Repository? = null
|
||||||
|
|
||||||
|
try {
|
||||||
|
val unmergedProducts = mutableListOf<Product>()
|
||||||
|
val unmergedReleases = mutableListOf<Pair<String, List<Release>>>()
|
||||||
|
IndexMerger(mergerFile).use { indexMerger ->
|
||||||
|
jarFile.getInputStream(indexEntry).getProgress {
|
||||||
|
callback(Stage.PROCESS, it, total)
|
||||||
|
}.use { entryStream ->
|
||||||
|
IndexV1Parser.parse(
|
||||||
|
repository.id,
|
||||||
|
entryStream,
|
||||||
|
object : IndexV1Parser.Callback {
|
||||||
|
override fun onRepository(
|
||||||
|
mirrors: List<String>,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
version: Int,
|
||||||
|
timestamp: Long
|
||||||
|
) {
|
||||||
|
changedRepository = repository.update(
|
||||||
|
mirrors,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
version,
|
||||||
|
lastModified,
|
||||||
|
entityTag,
|
||||||
|
timestamp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onProduct(product: Product) {
|
||||||
|
if (Thread.interrupted()) {
|
||||||
|
throw InterruptedException()
|
||||||
|
}
|
||||||
|
unmergedProducts += product
|
||||||
|
if (unmergedProducts.size >= 50) {
|
||||||
|
indexMerger.addProducts(unmergedProducts)
|
||||||
|
unmergedProducts.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReleases(
|
||||||
|
packageName: String,
|
||||||
|
releases: List<Release>
|
||||||
|
) {
|
||||||
|
if (Thread.interrupted()) {
|
||||||
|
throw InterruptedException()
|
||||||
|
}
|
||||||
|
unmergedReleases += Pair(packageName, releases)
|
||||||
|
if (unmergedReleases.size >= 50) {
|
||||||
|
indexMerger.addReleases(unmergedReleases)
|
||||||
|
unmergedReleases.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (Thread.interrupted()) {
|
||||||
|
throw InterruptedException()
|
||||||
|
}
|
||||||
|
if (unmergedProducts.isNotEmpty()) {
|
||||||
|
indexMerger.addProducts(unmergedProducts)
|
||||||
|
unmergedProducts.clear()
|
||||||
|
}
|
||||||
|
if (unmergedReleases.isNotEmpty()) {
|
||||||
|
indexMerger.addReleases(unmergedReleases)
|
||||||
|
unmergedReleases.clear()
|
||||||
|
}
|
||||||
|
var progress = 0
|
||||||
|
indexMerger.forEach(repository.id, 50) { products, totalCount ->
|
||||||
|
if (Thread.interrupted()) {
|
||||||
|
throw InterruptedException()
|
||||||
|
}
|
||||||
|
progress += products.size
|
||||||
|
callback(
|
||||||
|
Stage.MERGE,
|
||||||
|
progress.toLong(),
|
||||||
|
totalCount.toLong()
|
||||||
|
)
|
||||||
|
Database.UpdaterAdapter.putTemporary(
|
||||||
|
products
|
||||||
|
.map { transformProduct(it, features, unstable) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
mergerFile.delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
val workRepository = changedRepository ?: repository
|
||||||
|
if (workRepository.timestamp < repository.timestamp) {
|
||||||
|
throw UpdateException(
|
||||||
|
ErrorType.VALIDATION,
|
||||||
|
"New index is older than current index:" +
|
||||||
|
" ${workRepository.timestamp} < ${repository.timestamp}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val fingerprint = indexEntry
|
||||||
|
.codeSigner
|
||||||
|
.certificate
|
||||||
|
.fingerprint()
|
||||||
|
.toString()
|
||||||
|
.uppercase()
|
||||||
|
|
||||||
|
val commitRepository = if (!workRepository.fingerprint.equals(
|
||||||
|
fingerprint,
|
||||||
|
ignoreCase = true
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
if (workRepository.fingerprint.isNotEmpty()) {
|
||||||
|
throw UpdateException(
|
||||||
|
ErrorType.VALIDATION,
|
||||||
|
"Certificate fingerprints do not match"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
workRepository.copy(fingerprint = fingerprint)
|
||||||
|
} else {
|
||||||
|
workRepository
|
||||||
|
}
|
||||||
|
if (Thread.interrupted()) {
|
||||||
|
throw InterruptedException()
|
||||||
|
}
|
||||||
|
callback(Stage.COMMIT, 0, null)
|
||||||
|
synchronized(cleanupLock) {
|
||||||
|
Database.UpdaterAdapter.finishTemporary(commitRepository, true)
|
||||||
|
}
|
||||||
|
rollback = false
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw when (e) {
|
||||||
|
is UpdateException, is InterruptedException -> e
|
||||||
|
else -> UpdateException(ErrorType.PARSING, "Error parsing index", e)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
file.delete()
|
||||||
|
if (rollback) {
|
||||||
|
Database.UpdaterAdapter.finishTemporary(repository, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@get:Throws(UpdateException::class)
|
||||||
|
private val JarEntry.codeSigner: CodeSigner
|
||||||
|
get() = codeSigners?.singleOrNull()
|
||||||
|
?: throw UpdateException(
|
||||||
|
ErrorType.VALIDATION,
|
||||||
|
"index.jar must be signed by a single code signer"
|
||||||
|
)
|
||||||
|
|
||||||
|
@get:Throws(UpdateException::class)
|
||||||
|
private val CodeSigner.certificate: Certificate
|
||||||
|
get() = signerCertPath?.certificates?.singleOrNull()
|
||||||
|
?: throw UpdateException(
|
||||||
|
ErrorType.VALIDATION,
|
||||||
|
"index.jar code signer should have only one certificate"
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun transformProduct(
|
||||||
|
product: Product,
|
||||||
|
features: Set<String>,
|
||||||
|
unstable: Boolean
|
||||||
|
): Product {
|
||||||
|
val releasePairs = product.releases
|
||||||
|
.distinctBy { it.identifier }
|
||||||
|
.sortedByDescending { it.versionCode }
|
||||||
|
.map { release ->
|
||||||
|
val incompatibilities = mutableListOf<Release.Incompatibility>()
|
||||||
|
if (release.minSdkVersion > 0 && SdkCheck.sdk < release.minSdkVersion) {
|
||||||
|
incompatibilities += Release.Incompatibility.MinSdk
|
||||||
|
}
|
||||||
|
if (release.maxSdkVersion > 0 && SdkCheck.sdk > release.maxSdkVersion) {
|
||||||
|
incompatibilities += Release.Incompatibility.MaxSdk
|
||||||
|
}
|
||||||
|
if (release.platforms.isNotEmpty() &&
|
||||||
|
(release.platforms intersect Android.platforms).isEmpty()
|
||||||
|
) {
|
||||||
|
incompatibilities += Release.Incompatibility.Platform
|
||||||
|
}
|
||||||
|
incompatibilities += (release.features - features).sorted()
|
||||||
|
.map { Release.Incompatibility.Feature(it) }
|
||||||
|
Pair(release, incompatibilities.toList())
|
||||||
|
}
|
||||||
|
|
||||||
|
val predicate: (Release) -> Boolean = {
|
||||||
|
unstable ||
|
||||||
|
product.suggestedVersionCode <= 0 ||
|
||||||
|
it.versionCode <= product.suggestedVersionCode
|
||||||
|
}
|
||||||
|
|
||||||
|
val firstSelected =
|
||||||
|
releasePairs.firstOrNull { it.second.isEmpty() && predicate(it.first) }
|
||||||
|
?: releasePairs.firstOrNull { predicate(it.first) }
|
||||||
|
|
||||||
|
val releases = releasePairs
|
||||||
|
.map { (release, incompatibilities) ->
|
||||||
|
release.copy(
|
||||||
|
incompatibilities = incompatibilities,
|
||||||
|
selected = firstSelected?.let {
|
||||||
|
it.first.versionCode == release.versionCode &&
|
||||||
|
it.second == incompatibilities
|
||||||
|
} ?: false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return product.copy(releases = releases)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class IndexFile(
|
||||||
|
val isUnmodified: Boolean,
|
||||||
|
val lastModified: String,
|
||||||
|
val entityTag: String,
|
||||||
|
val statusCode: Int,
|
||||||
|
val file: File
|
||||||
|
)
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.looker.droidify.installer
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.looker.droidify.utility.common.extension.addAndCompute
|
||||||
|
import com.looker.droidify.utility.common.extension.filter
|
||||||
|
import com.looker.droidify.utility.common.extension.notificationManager
|
||||||
|
import com.looker.droidify.utility.common.extension.updateAsMutable
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.datastore.get
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.installers.Installer
|
||||||
|
import com.looker.droidify.installer.installers.LegacyInstaller
|
||||||
|
import com.looker.droidify.installer.installers.root.RootInstaller
|
||||||
|
import com.looker.droidify.installer.installers.session.SessionInstaller
|
||||||
|
import com.looker.droidify.installer.installers.shizuku.ShizukuInstaller
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.installer.notification.createInstallNotification
|
||||||
|
import com.looker.droidify.installer.notification.installNotification
|
||||||
|
import com.looker.droidify.installer.notification.removeInstallNotification
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.channels.consumeEach
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
|
||||||
|
class InstallManager(
|
||||||
|
private val context: Context,
|
||||||
|
settingsRepository: SettingsRepository
|
||||||
|
) {
|
||||||
|
|
||||||
|
private val installItems = Channel<InstallItem>()
|
||||||
|
private val uninstallItems = Channel<PackageName>()
|
||||||
|
|
||||||
|
val state = MutableStateFlow<Map<PackageName, InstallState>>(emptyMap())
|
||||||
|
|
||||||
|
private var _installer: Installer? = null
|
||||||
|
set(value) {
|
||||||
|
field?.close()
|
||||||
|
field = value
|
||||||
|
}
|
||||||
|
private val installer: Installer get() = _installer!!
|
||||||
|
|
||||||
|
private val lock = Mutex()
|
||||||
|
private val installerPreference = settingsRepository.get { installerType }
|
||||||
|
|
||||||
|
suspend operator fun invoke() = coroutineScope {
|
||||||
|
setupInstaller()
|
||||||
|
installer()
|
||||||
|
uninstaller()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
_installer = null
|
||||||
|
uninstallItems.close()
|
||||||
|
installItems.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend infix fun install(installItem: InstallItem) {
|
||||||
|
installItems.send(installItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend infix fun uninstall(packageName: PackageName) {
|
||||||
|
uninstallItems.send(packageName)
|
||||||
|
}
|
||||||
|
|
||||||
|
infix fun remove(packageName: PackageName) {
|
||||||
|
updateState { remove(packageName) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun CoroutineScope.setupInstaller() = launch {
|
||||||
|
installerPreference.collectLatest(::setInstaller)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun CoroutineScope.installer() = launch {
|
||||||
|
val currentQueue = mutableSetOf<String>()
|
||||||
|
installItems.filter { item ->
|
||||||
|
currentQueue.addAndCompute(item.packageName.name) { isAdded ->
|
||||||
|
if (isAdded) {
|
||||||
|
updateState { put(item.packageName, InstallState.Pending) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.consumeEach { item ->
|
||||||
|
if (state.value.containsKey(item.packageName)) {
|
||||||
|
updateState { put(item.packageName, InstallState.Installing) }
|
||||||
|
context.notificationManager?.installNotification(
|
||||||
|
packageName = item.packageName.name,
|
||||||
|
notification = context.createInstallNotification(
|
||||||
|
appName = item.packageName.name,
|
||||||
|
state = InstallState.Installing,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
val success = installer.use {
|
||||||
|
it.install(item)
|
||||||
|
}
|
||||||
|
context.notificationManager?.removeInstallNotification(item.packageName.name)
|
||||||
|
updateState { put(item.packageName, success) }
|
||||||
|
currentQueue.remove(item.packageName.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun CoroutineScope.uninstaller() = launch {
|
||||||
|
uninstallItems.consumeEach {
|
||||||
|
installer.uninstall(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun setInstaller(installerType: InstallerType) {
|
||||||
|
lock.withLock {
|
||||||
|
_installer = when (installerType) {
|
||||||
|
InstallerType.LEGACY -> LegacyInstaller(context)
|
||||||
|
InstallerType.SESSION -> SessionInstaller(context)
|
||||||
|
InstallerType.SHIZUKU -> ShizukuInstaller(context)
|
||||||
|
InstallerType.ROOT -> RootInstaller(context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun updateState(block: MutableMap<PackageName, InstallState>.() -> Unit) {
|
||||||
|
state.update { it.updateAsMutable(block) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.looker.droidify.installer.installers
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
|
||||||
|
interface Installer : AutoCloseable {
|
||||||
|
|
||||||
|
suspend fun install(installItem: InstallItem): InstallState
|
||||||
|
|
||||||
|
suspend fun uninstall(packageName: PackageName)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package com.looker.droidify.installer.installers
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import com.looker.droidify.utility.common.extension.getLauncherActivities
|
||||||
|
import com.looker.droidify.utility.common.extension.getPackageInfoCompat
|
||||||
|
import com.looker.droidify.utility.common.extension.intent
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import rikka.shizuku.ShizukuProvider
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
private const val SHIZUKU_PERMISSION_REQUEST_CODE = 87263
|
||||||
|
|
||||||
|
fun launchShizuku(context: Context) {
|
||||||
|
val activities =
|
||||||
|
context.packageManager.getLauncherActivities(ShizukuProvider.MANAGER_APPLICATION_ID)
|
||||||
|
val intent = intent(Intent.ACTION_MAIN) {
|
||||||
|
addCategory(Intent.CATEGORY_LAUNCHER)
|
||||||
|
setComponent(
|
||||||
|
ComponentName(
|
||||||
|
ShizukuProvider.MANAGER_APPLICATION_ID,
|
||||||
|
activities.first().first
|
||||||
|
)
|
||||||
|
)
|
||||||
|
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isShizukuInstalled(context: Context) =
|
||||||
|
context.packageManager.getPackageInfoCompat(ShizukuProvider.MANAGER_APPLICATION_ID) != null
|
||||||
|
|
||||||
|
fun isShizukuAlive() = rikka.shizuku.Shizuku.pingBinder()
|
||||||
|
|
||||||
|
fun isShizukuGranted() = rikka.shizuku.Shizuku.checkSelfPermission() == PackageManager.PERMISSION_GRANTED
|
||||||
|
|
||||||
|
suspend fun requestPermissionListener() = suspendCancellableCoroutine {
|
||||||
|
val listener = rikka.shizuku.Shizuku.OnRequestPermissionResultListener { requestCode, grantResult ->
|
||||||
|
if (requestCode == SHIZUKU_PERMISSION_REQUEST_CODE) {
|
||||||
|
it.resume(grantResult == PackageManager.PERMISSION_GRANTED)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rikka.shizuku.Shizuku.addRequestPermissionResultListener(listener)
|
||||||
|
rikka.shizuku.Shizuku.requestPermission(SHIZUKU_PERMISSION_REQUEST_CODE)
|
||||||
|
it.invokeOnCancellation {
|
||||||
|
rikka.shizuku.Shizuku.removeRequestPermissionResultListener(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requestShizuku() {
|
||||||
|
rikka.shizuku.Shizuku.shouldShowRequestPermissionRationale()
|
||||||
|
rikka.shizuku.Shizuku.requestPermission(SHIZUKU_PERMISSION_REQUEST_CODE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isMagiskGranted(): Boolean {
|
||||||
|
com.topjohnwu.superuser.Shell.getCachedShell() ?: com.topjohnwu.superuser.Shell.getShell()
|
||||||
|
return com.topjohnwu.superuser.Shell.isAppGrantedRoot() == true
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.looker.droidify.installer.installers
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.util.AndroidRuntimeException
|
||||||
|
import androidx.core.net.toUri
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.extension.intent
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
class LegacyInstaller(private val context: Context) : Installer {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val APK_MIME = "application/vnd.android.package-archive"
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun install(
|
||||||
|
installItem: InstallItem,
|
||||||
|
): InstallState = suspendCancellableCoroutine { cont ->
|
||||||
|
val installFlag = if (SdkCheck.isNougat) Intent.FLAG_GRANT_READ_URI_PERMISSION else 0
|
||||||
|
val fileUri = if (SdkCheck.isNougat) {
|
||||||
|
Cache.getReleaseUri(
|
||||||
|
context,
|
||||||
|
installItem.installFileName
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Cache.getReleaseFile(context, installItem.installFileName).toUri()
|
||||||
|
}
|
||||||
|
val installIntent = intent(Intent.ACTION_INSTALL_PACKAGE) {
|
||||||
|
setDataAndType(fileUri, APK_MIME)
|
||||||
|
flags = installFlag
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
context.startActivity(installIntent)
|
||||||
|
cont.resume(InstallState.Installed)
|
||||||
|
} catch (e: AndroidRuntimeException) {
|
||||||
|
installIntent.flags = installFlag or Intent.FLAG_ACTIVITY_NEW_TASK
|
||||||
|
context.startActivity(installIntent)
|
||||||
|
cont.resume(InstallState.Installed)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
cont.resume(InstallState.Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun uninstall(packageName: PackageName) =
|
||||||
|
context.uninstallPackage(packageName)
|
||||||
|
|
||||||
|
override fun close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun Context.uninstallPackage(packageName: PackageName) =
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
try {
|
||||||
|
startActivity(
|
||||||
|
intent(Intent.ACTION_UNINSTALL_PACKAGE) {
|
||||||
|
data = "package:${packageName.name}".toUri()
|
||||||
|
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||||
|
}
|
||||||
|
)
|
||||||
|
cont.resume(Unit)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
cont.resume(Unit)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package com.looker.droidify.installer.installers.root
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.installers.Installer
|
||||||
|
import com.looker.droidify.installer.installers.uninstallPackage
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.topjohnwu.superuser.Shell
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
class RootInstaller(private val context: Context) : Installer {
|
||||||
|
|
||||||
|
override suspend fun install(
|
||||||
|
installItem: InstallItem,
|
||||||
|
): InstallState = suspendCancellableCoroutine { cont ->
|
||||||
|
val releaseFile = Cache.getReleaseFile(context, installItem.installFileName)
|
||||||
|
val installCommand = INSTALL_COMMAND.format(
|
||||||
|
releaseFile.absolutePath,
|
||||||
|
currentUser(),
|
||||||
|
releaseFile.length(),
|
||||||
|
)
|
||||||
|
Shell.cmd(installCommand).submit { shellResult ->
|
||||||
|
val result = if (shellResult.isSuccess) InstallState.Installed
|
||||||
|
else InstallState.Failed
|
||||||
|
cont.resume(result)
|
||||||
|
val deleteCommand = DELETE_COMMAND.format(utilBox(), releaseFile.absolutePath)
|
||||||
|
Shell.cmd(deleteCommand).submit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun uninstall(packageName: PackageName) =
|
||||||
|
context.uninstallPackage(packageName)
|
||||||
|
|
||||||
|
override fun close() {}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val INSTALL_COMMAND = "cat %s | pm install --user %s -t -r -S %s"
|
||||||
|
private const val DELETE_COMMAND = "%s rm %s"
|
||||||
|
|
||||||
|
/** Returns the path of either toybox or busybox, or empty string if not found. */
|
||||||
|
private fun utilBox(): String {
|
||||||
|
listOf("toybox", "busybox").forEach {
|
||||||
|
// Returns the path of the requested [command], or empty string if not found
|
||||||
|
val out = Shell.cmd("which $it").exec().out
|
||||||
|
if (out.isEmpty()) return ""
|
||||||
|
if (out.first().contains("not found")) return ""
|
||||||
|
return out.first()
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the current user of the device. */
|
||||||
|
private fun currentUser() = if (SdkCheck.isOreo) {
|
||||||
|
Shell.cmd("am get-current-user")
|
||||||
|
.exec()
|
||||||
|
.out[0]
|
||||||
|
} else {
|
||||||
|
Shell.cmd("dumpsys activity | grep -E \"mUserLru\"")
|
||||||
|
.exec()
|
||||||
|
.out[0]
|
||||||
|
.trim()
|
||||||
|
.removePrefix("mUserLru: [")
|
||||||
|
.removeSuffix("]")
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package com.looker.droidify.installer.installers.session
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageInstaller
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.log
|
||||||
|
import com.looker.droidify.utility.common.sdkAbove
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.installers.Installer
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
class SessionInstaller(private val context: Context) : Installer {
|
||||||
|
|
||||||
|
private val installer = context.packageManager.packageInstaller
|
||||||
|
private val intent = Intent(context, SessionInstallerReceiver::class.java)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private var installerCallbacks: PackageInstaller.SessionCallback? = null
|
||||||
|
private val flags = if (SdkCheck.isSnowCake) PendingIntent.FLAG_MUTABLE else 0
|
||||||
|
private val sessionParams =
|
||||||
|
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {
|
||||||
|
sdkAbove(sdk = Build.VERSION_CODES.S) {
|
||||||
|
setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED)
|
||||||
|
}
|
||||||
|
sdkAbove(sdk = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||||
|
setRequestUpdateOwnership(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun install(
|
||||||
|
installItem: InstallItem
|
||||||
|
): InstallState = suspendCancellableCoroutine { cont ->
|
||||||
|
val cacheFile = Cache.getReleaseFile(context, installItem.installFileName)
|
||||||
|
val id = installer.createSession(sessionParams)
|
||||||
|
val installerCallback = object : PackageInstaller.SessionCallback() {
|
||||||
|
override fun onCreated(sessionId: Int) {}
|
||||||
|
override fun onBadgingChanged(sessionId: Int) {}
|
||||||
|
override fun onActiveChanged(sessionId: Int, active: Boolean) {}
|
||||||
|
override fun onProgressChanged(sessionId: Int, progress: Float) {}
|
||||||
|
override fun onFinished(sessionId: Int, success: Boolean) {
|
||||||
|
if (sessionId == id) cont.resume(InstallState.Installed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
installerCallbacks = installerCallback
|
||||||
|
|
||||||
|
installer.registerSessionCallback(
|
||||||
|
installerCallbacks!!,
|
||||||
|
Handler(Looper.getMainLooper())
|
||||||
|
)
|
||||||
|
|
||||||
|
val session = installer.openSession(id)
|
||||||
|
|
||||||
|
session.use { activeSession ->
|
||||||
|
val sizeBytes = cacheFile.length()
|
||||||
|
cacheFile.inputStream().use { fileStream ->
|
||||||
|
activeSession.openWrite(cacheFile.name, 0, sizeBytes).use { outputStream ->
|
||||||
|
if (cont.isActive) {
|
||||||
|
fileStream.copyTo(outputStream)
|
||||||
|
activeSession.fsync(outputStream)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val pendingIntent = PendingIntent.getBroadcast(context, id, intent, flags)
|
||||||
|
|
||||||
|
if (cont.isActive) activeSession.commit(pendingIntent.intentSender)
|
||||||
|
}
|
||||||
|
|
||||||
|
cont.invokeOnCancellation {
|
||||||
|
try {
|
||||||
|
installer.abandonSession(id)
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("MissingPermission")
|
||||||
|
override suspend fun uninstall(packageName: PackageName) =
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
intent.putExtra(SessionInstallerReceiver.ACTION_UNINSTALL, true)
|
||||||
|
val pendingIntent = PendingIntent.getBroadcast(context, -1, intent, flags)
|
||||||
|
|
||||||
|
installer.uninstall(packageName.name, pendingIntent.intentSender)
|
||||||
|
cont.resume(Unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
installerCallbacks?.let {
|
||||||
|
installer.unregisterSessionCallback(it)
|
||||||
|
installerCallbacks = null
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
installer.mySessions.forEach { installer.abandonSession(it.sessionId) }
|
||||||
|
} catch (e: SecurityException) {
|
||||||
|
log(e.message, type = Log.ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package com.looker.droidify.installer.installers.session
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageInstaller
|
||||||
|
import com.looker.droidify.utility.common.Constants.NOTIFICATION_CHANNEL_INSTALL
|
||||||
|
import com.looker.droidify.R
|
||||||
|
import com.looker.droidify.utility.common.createNotificationChannel
|
||||||
|
import com.looker.droidify.utility.common.extension.getPackageName
|
||||||
|
import com.looker.droidify.utility.common.extension.notificationManager
|
||||||
|
import com.looker.droidify.domain.model.toPackageName
|
||||||
|
import com.looker.droidify.installer.InstallManager
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.installer.notification.createInstallNotification
|
||||||
|
import com.looker.droidify.installer.notification.installNotification
|
||||||
|
import com.looker.droidify.installer.notification.removeInstallNotification
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class SessionInstallerReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
// This is a cyclic dependency injection, I know but this is the best option for now
|
||||||
|
@Inject
|
||||||
|
lateinit var installManager: InstallManager
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)
|
||||||
|
|
||||||
|
if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) {
|
||||||
|
// prompts user to enable unknown source
|
||||||
|
val promptIntent: Intent? = intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||||
|
|
||||||
|
promptIntent?.let {
|
||||||
|
it.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
|
||||||
|
it.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, "com.android.vending")
|
||||||
|
it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
|
||||||
|
context.startActivity(it)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
notifyStatus(intent, context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notifyStatus(intent: Intent, context: Context) {
|
||||||
|
val packageManager = context.packageManager
|
||||||
|
val notificationManager = context.notificationManager
|
||||||
|
|
||||||
|
context.createNotificationChannel(
|
||||||
|
id = NOTIFICATION_CHANNEL_INSTALL,
|
||||||
|
name = context.getString(R.string.install)
|
||||||
|
)
|
||||||
|
|
||||||
|
val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -1)
|
||||||
|
val packageName = intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)
|
||||||
|
val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE)
|
||||||
|
val isUninstall = intent.getBooleanExtra(ACTION_UNINSTALL, false)
|
||||||
|
|
||||||
|
val appName = packageManager.getPackageName(packageName)
|
||||||
|
|
||||||
|
if (packageName != null) {
|
||||||
|
when (status) {
|
||||||
|
PackageInstaller.STATUS_SUCCESS -> {
|
||||||
|
notificationManager?.removeInstallNotification(packageName)
|
||||||
|
val notification = context.createInstallNotification(
|
||||||
|
appName = (appName ?: packageName.substringAfterLast('.')).toString(),
|
||||||
|
state = InstallState.Installed,
|
||||||
|
isUninstall = isUninstall,
|
||||||
|
) {
|
||||||
|
setTimeoutAfter(SUCCESS_TIMEOUT)
|
||||||
|
}
|
||||||
|
notificationManager?.installNotification(
|
||||||
|
packageName = packageName.toString(),
|
||||||
|
notification = notification,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
PackageInstaller.STATUS_FAILURE_ABORTED -> {
|
||||||
|
installManager.remove(packageName.toPackageName())
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
installManager.remove(packageName.toPackageName())
|
||||||
|
val notification = context.createInstallNotification(
|
||||||
|
appName = appName.toString(),
|
||||||
|
state = InstallState.Failed,
|
||||||
|
) {
|
||||||
|
setContentText(message)
|
||||||
|
}
|
||||||
|
notificationManager?.installNotification(
|
||||||
|
packageName = packageName,
|
||||||
|
notification = notification
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_UNINSTALL = "action_uninstall"
|
||||||
|
|
||||||
|
private const val SUCCESS_TIMEOUT = 5_000L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.looker.droidify.installer.installers.shizuku
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.extension.size
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.installer.installers.Installer
|
||||||
|
import com.looker.droidify.installer.installers.uninstallPackage
|
||||||
|
import com.looker.droidify.installer.model.InstallItem
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.InputStream
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
class ShizukuInstaller(private val context: Context) : Installer {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private val SESSION_ID_REGEX = Regex("(?<=\\[).+?(?=])")
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun install(
|
||||||
|
installItem: InstallItem
|
||||||
|
): InstallState = suspendCancellableCoroutine { cont ->
|
||||||
|
var sessionId: String? = null
|
||||||
|
val file = Cache.getReleaseFile(context, installItem.installFileName)
|
||||||
|
val packageName = installItem.packageName.name
|
||||||
|
try {
|
||||||
|
val fileSize = file.size ?: run {
|
||||||
|
cont.cancel()
|
||||||
|
error("File is not valid: Size ${file.size}")
|
||||||
|
}
|
||||||
|
if (cont.isCompleted) return@suspendCancellableCoroutine
|
||||||
|
file.inputStream().use {
|
||||||
|
val createCommand =
|
||||||
|
if (SdkCheck.isNougat) {
|
||||||
|
"pm install-create --user current -i $packageName -S $fileSize"
|
||||||
|
} else {
|
||||||
|
"pm install-create -i $packageName -S $fileSize"
|
||||||
|
}
|
||||||
|
val createResult = exec(createCommand)
|
||||||
|
sessionId = SESSION_ID_REGEX.find(createResult.out)?.value
|
||||||
|
?: run {
|
||||||
|
cont.cancel()
|
||||||
|
throw RuntimeException("Failed to create install session")
|
||||||
|
}
|
||||||
|
if (cont.isCompleted) return@suspendCancellableCoroutine
|
||||||
|
|
||||||
|
val writeResult = exec("pm install-write -S $fileSize $sessionId base -", it)
|
||||||
|
if (writeResult.resultCode != 0) {
|
||||||
|
cont.cancel()
|
||||||
|
throw RuntimeException("Failed to write APK to session $sessionId")
|
||||||
|
}
|
||||||
|
if (cont.isCompleted) return@suspendCancellableCoroutine
|
||||||
|
|
||||||
|
val commitResult = exec("pm install-commit $sessionId")
|
||||||
|
if (commitResult.resultCode != 0) {
|
||||||
|
cont.cancel()
|
||||||
|
throw RuntimeException("Failed to commit install session $sessionId")
|
||||||
|
}
|
||||||
|
if (cont.isCompleted) return@suspendCancellableCoroutine
|
||||||
|
cont.resume(InstallState.Installed)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (sessionId != null) exec("pm install-abandon $sessionId")
|
||||||
|
cont.resume(InstallState.Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun uninstall(packageName: PackageName) =
|
||||||
|
context.uninstallPackage(packageName)
|
||||||
|
|
||||||
|
override fun close() {}
|
||||||
|
|
||||||
|
private data class ShellResult(val resultCode: Int, val out: String)
|
||||||
|
|
||||||
|
private fun exec(command: String, stdin: InputStream? = null): ShellResult {
|
||||||
|
val process = rikka.shizuku.Shizuku.newProcess(arrayOf("sh", "-c", command), null, null)
|
||||||
|
if (stdin != null) {
|
||||||
|
process.outputStream.use { stdin.copyTo(it) }
|
||||||
|
}
|
||||||
|
val output = process.inputStream.bufferedReader().use(BufferedReader::readText)
|
||||||
|
val resultCode = process.waitFor()
|
||||||
|
return ShellResult(resultCode, output)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.looker.droidify.installer.model
|
||||||
|
|
||||||
|
import com.looker.droidify.domain.model.PackageName
|
||||||
|
import com.looker.droidify.domain.model.toPackageName
|
||||||
|
|
||||||
|
class InstallItem(
|
||||||
|
val packageName: PackageName,
|
||||||
|
val installFileName: String
|
||||||
|
)
|
||||||
|
|
||||||
|
infix fun String.installFrom(fileName: String) = InstallItem(this.toPackageName(), fileName)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.looker.droidify.installer.model
|
||||||
|
|
||||||
|
enum class InstallState { Failed, Pending, Installing, Installed }
|
||||||
|
|
||||||
|
inline val InstallState.isCancellable: Boolean
|
||||||
|
get() = this == InstallState.Pending
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.looker.droidify.installer.notification
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import com.looker.droidify.utility.common.Constants.NOTIFICATION_CHANNEL_INSTALL
|
||||||
|
import com.looker.droidify.utility.common.Constants.NOTIFICATION_ID_INSTALL
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.R
|
||||||
|
|
||||||
|
fun NotificationManager.installNotification(
|
||||||
|
packageName: String,
|
||||||
|
notification: Notification,
|
||||||
|
) {
|
||||||
|
notify(
|
||||||
|
installTag(packageName),
|
||||||
|
NOTIFICATION_ID_INSTALL,
|
||||||
|
notification
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun NotificationManager.removeInstallNotification(
|
||||||
|
packageName: String,
|
||||||
|
) {
|
||||||
|
cancel(installTag(packageName), NOTIFICATION_ID_INSTALL)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installTag(name: String): String = "install-${name.trim().replace(' ', '_')}"
|
||||||
|
|
||||||
|
private const val SUCCESS_TIMEOUT = 5_000L
|
||||||
|
|
||||||
|
fun Context.createInstallNotification(
|
||||||
|
appName: String,
|
||||||
|
state: InstallState,
|
||||||
|
isUninstall: Boolean = false,
|
||||||
|
autoCancel: Boolean = true,
|
||||||
|
block: NotificationCompat.Builder.() -> Unit = {},
|
||||||
|
): Notification {
|
||||||
|
return NotificationCompat
|
||||||
|
.Builder(this, NOTIFICATION_CHANNEL_INSTALL)
|
||||||
|
.apply {
|
||||||
|
setAutoCancel(autoCancel)
|
||||||
|
setOngoing(false)
|
||||||
|
setOnlyAlertOnce(true)
|
||||||
|
setColor(Color.GREEN)
|
||||||
|
val (title, text) = if (isUninstall) {
|
||||||
|
setTimeoutAfter(SUCCESS_TIMEOUT)
|
||||||
|
setSmallIcon(R.drawable.ic_delete)
|
||||||
|
getString(R.string.uninstalled_application) to
|
||||||
|
getString(R.string.uninstalled_application_DESC, appName)
|
||||||
|
} else {
|
||||||
|
when (state) {
|
||||||
|
InstallState.Failed -> {
|
||||||
|
setSmallIcon(R.drawable.ic_bug_report)
|
||||||
|
getString(R.string.installation_failed) to
|
||||||
|
getString(R.string.installation_failed_DESC, appName)
|
||||||
|
}
|
||||||
|
|
||||||
|
InstallState.Pending -> {
|
||||||
|
setSmallIcon(R.drawable.ic_download)
|
||||||
|
getString(R.string.downloaded_FORMAT, appName) to
|
||||||
|
getString(R.string.tap_to_install_DESC)
|
||||||
|
}
|
||||||
|
|
||||||
|
InstallState.Installing -> {
|
||||||
|
setSmallIcon(R.drawable.ic_download)
|
||||||
|
setProgress(-1, -1, true)
|
||||||
|
getString(R.string.installing) to
|
||||||
|
appName
|
||||||
|
}
|
||||||
|
|
||||||
|
InstallState.Installed -> {
|
||||||
|
setTimeoutAfter(SUCCESS_TIMEOUT)
|
||||||
|
setSmallIcon(R.drawable.ic_check)
|
||||||
|
getString(R.string.installed) to
|
||||||
|
appName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setContentTitle(title)
|
||||||
|
setContentText(text)
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
.build()
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
class InstalledItem(
|
||||||
|
val packageName: String,
|
||||||
|
val version: String,
|
||||||
|
val versionCode: Long,
|
||||||
|
val signature: String
|
||||||
|
)
|
||||||
128
app/src/main/kotlin/com/looker/droidify/model/Product.kt
Normal file
128
app/src/main/kotlin/com/looker/droidify/model/Product.kt
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.looker.droidify.utility.common.extension.getColorFromAttr
|
||||||
|
import com.looker.droidify.utility.common.extension.videoPlaceHolder
|
||||||
|
import com.google.android.material.R as MaterialR
|
||||||
|
|
||||||
|
data class Product(
|
||||||
|
var repositoryId: Long,
|
||||||
|
val packageName: String,
|
||||||
|
val name: String,
|
||||||
|
val summary: String,
|
||||||
|
var description: String,
|
||||||
|
val whatsNew: String,
|
||||||
|
val icon: String,
|
||||||
|
val metadataIcon: String,
|
||||||
|
val author: Author,
|
||||||
|
val source: String,
|
||||||
|
val changelog: String,
|
||||||
|
val web: String,
|
||||||
|
val tracker: String,
|
||||||
|
val added: Long,
|
||||||
|
val updated: Long,
|
||||||
|
val suggestedVersionCode: Long,
|
||||||
|
val categories: List<String>,
|
||||||
|
val antiFeatures: List<String>,
|
||||||
|
val licenses: List<String>,
|
||||||
|
val donates: List<Donate>,
|
||||||
|
val screenshots: List<Screenshot>,
|
||||||
|
val releases: List<Release>
|
||||||
|
) {
|
||||||
|
data class Author(val name: String, val email: String, val web: String)
|
||||||
|
|
||||||
|
sealed class Donate {
|
||||||
|
data class Regular(val url: String) : Donate()
|
||||||
|
data class Bitcoin(val address: String) : Donate()
|
||||||
|
data class Litecoin(val address: String) : Donate()
|
||||||
|
data class Liberapay(val id: String) : Donate()
|
||||||
|
data class OpenCollective(val id: String) : Donate()
|
||||||
|
}
|
||||||
|
|
||||||
|
class Screenshot(val locale: String, val type: Type, val path: String) {
|
||||||
|
enum class Type(val jsonName: String) {
|
||||||
|
VIDEO("video"),
|
||||||
|
PHONE("phone"),
|
||||||
|
SMALL_TABLET("smallTablet"),
|
||||||
|
LARGE_TABLET("largeTablet"),
|
||||||
|
WEAR("wear"),
|
||||||
|
TV("tv")
|
||||||
|
}
|
||||||
|
|
||||||
|
val identifier: String
|
||||||
|
get() = "$locale.${type.name}.$path"
|
||||||
|
|
||||||
|
fun url(
|
||||||
|
context: Context,
|
||||||
|
repository: Repository,
|
||||||
|
packageName: String
|
||||||
|
): Any {
|
||||||
|
if (type == Type.VIDEO) return context.videoPlaceHolder.apply {
|
||||||
|
setTintList(context.getColorFromAttr(MaterialR.attr.colorOnSurfaceInverse))
|
||||||
|
}
|
||||||
|
val phoneType = when (type) {
|
||||||
|
Type.PHONE -> "phoneScreenshots"
|
||||||
|
Type.SMALL_TABLET -> "sevenInchScreenshots"
|
||||||
|
Type.LARGE_TABLET -> "tenInchScreenshots"
|
||||||
|
Type.WEAR -> "wearScreenshots"
|
||||||
|
Type.TV -> "tvScreenshots"
|
||||||
|
else -> error("Should not be here, video url already returned")
|
||||||
|
}
|
||||||
|
return "${repository.address}/$packageName/$locale/$phoneType/$path"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same releases with different signatures
|
||||||
|
val selectedReleases: List<Release>
|
||||||
|
get() = releases.filter { it.selected }
|
||||||
|
|
||||||
|
val displayRelease: Release?
|
||||||
|
get() = selectedReleases.firstOrNull() ?: releases.firstOrNull()
|
||||||
|
|
||||||
|
val version: String
|
||||||
|
get() = displayRelease?.version.orEmpty()
|
||||||
|
|
||||||
|
val versionCode: Long
|
||||||
|
get() = selectedReleases.firstOrNull()?.versionCode ?: 0L
|
||||||
|
|
||||||
|
val compatible: Boolean
|
||||||
|
get() = selectedReleases.firstOrNull()?.incompatibilities?.isEmpty() == true
|
||||||
|
|
||||||
|
val signatures: List<String>
|
||||||
|
get() = selectedReleases.mapNotNull { it.signature.ifBlank { null } }.distinct().toList()
|
||||||
|
|
||||||
|
fun item(): ProductItem {
|
||||||
|
return ProductItem(
|
||||||
|
repositoryId,
|
||||||
|
packageName,
|
||||||
|
name,
|
||||||
|
summary,
|
||||||
|
icon,
|
||||||
|
metadataIcon,
|
||||||
|
version,
|
||||||
|
"",
|
||||||
|
compatible,
|
||||||
|
false,
|
||||||
|
0
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun canUpdate(installedItem: InstalledItem?): Boolean {
|
||||||
|
return installedItem != null && compatible && versionCode > installedItem.versionCode &&
|
||||||
|
installedItem.signature in signatures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun List<Pair<Product, Repository>>.findSuggested(
|
||||||
|
installedItem: InstalledItem?
|
||||||
|
): Pair<Product, Repository>? = maxWithOrNull(
|
||||||
|
compareBy(
|
||||||
|
{ (product, _) ->
|
||||||
|
product.compatible &&
|
||||||
|
(installedItem == null || installedItem.signature in product.signatures)
|
||||||
|
},
|
||||||
|
{ (product, _) ->
|
||||||
|
product.versionCode
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
56
app/src/main/kotlin/com/looker/droidify/model/ProductItem.kt
Normal file
56
app/src/main/kotlin/com/looker/droidify/model/ProductItem.kt
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
import android.os.Parcelable
|
||||||
|
import android.view.View
|
||||||
|
import com.looker.droidify.utility.common.extension.dpi
|
||||||
|
import kotlinx.parcelize.Parcelize
|
||||||
|
|
||||||
|
data class ProductItem(
|
||||||
|
var repositoryId: Long,
|
||||||
|
var packageName: String,
|
||||||
|
var name: String,
|
||||||
|
var summary: String,
|
||||||
|
val icon: String,
|
||||||
|
val metadataIcon: String,
|
||||||
|
val version: String,
|
||||||
|
var installedVersion: String,
|
||||||
|
var compatible: Boolean,
|
||||||
|
var canUpdate: Boolean,
|
||||||
|
var matchRank: Int
|
||||||
|
) {
|
||||||
|
sealed interface Section : Parcelable {
|
||||||
|
|
||||||
|
@Parcelize
|
||||||
|
object All : Section
|
||||||
|
|
||||||
|
@Parcelize
|
||||||
|
class Category(val name: String) : Section
|
||||||
|
|
||||||
|
@Parcelize
|
||||||
|
class Repository(val id: Long, val name: String) : Section
|
||||||
|
}
|
||||||
|
|
||||||
|
private val supportedDpi = intArrayOf(120, 160, 240, 320, 480, 640)
|
||||||
|
private var deviceDpi: Int = -1
|
||||||
|
|
||||||
|
fun icon(
|
||||||
|
view: View,
|
||||||
|
repository: Repository
|
||||||
|
): String? {
|
||||||
|
if (packageName.isBlank()) return null
|
||||||
|
if (icon.isBlank() && metadataIcon.isBlank()) return null
|
||||||
|
if (repository.version < 11 && icon.isNotBlank()) {
|
||||||
|
return "${repository.address}/icons/$icon"
|
||||||
|
}
|
||||||
|
if (icon.isNotBlank()) {
|
||||||
|
if (deviceDpi == -1) {
|
||||||
|
deviceDpi = supportedDpi.find { it >= view.dpi } ?: supportedDpi.last()
|
||||||
|
}
|
||||||
|
return "${repository.address}/icons-$deviceDpi/$icon"
|
||||||
|
}
|
||||||
|
if (metadataIcon.isNotBlank()) {
|
||||||
|
return "${repository.address}/$packageName/$metadataIcon"
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
data class ProductPreference(val ignoreUpdates: Boolean, val ignoreVersionCode: Long) {
|
||||||
|
fun shouldIgnoreUpdate(versionCode: Long): Boolean {
|
||||||
|
return ignoreUpdates || ignoreVersionCode == versionCode
|
||||||
|
}
|
||||||
|
}
|
||||||
46
app/src/main/kotlin/com/looker/droidify/model/Release.kt
Normal file
46
app/src/main/kotlin/com/looker/droidify/model/Release.kt
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
|
||||||
|
data class Release(
|
||||||
|
val selected: Boolean,
|
||||||
|
val version: String,
|
||||||
|
val versionCode: Long,
|
||||||
|
val added: Long,
|
||||||
|
val size: Long,
|
||||||
|
val minSdkVersion: Int,
|
||||||
|
val targetSdkVersion: Int,
|
||||||
|
val maxSdkVersion: Int,
|
||||||
|
val source: String,
|
||||||
|
val release: String,
|
||||||
|
val hash: String,
|
||||||
|
val hashType: String,
|
||||||
|
val signature: String,
|
||||||
|
val obbMain: String,
|
||||||
|
val obbMainHash: String,
|
||||||
|
val obbMainHashType: String,
|
||||||
|
val obbPatch: String,
|
||||||
|
val obbPatchHash: String,
|
||||||
|
val obbPatchHashType: String,
|
||||||
|
val permissions: List<String>,
|
||||||
|
val features: List<String>,
|
||||||
|
val platforms: List<String>,
|
||||||
|
val incompatibilities: List<Incompatibility>
|
||||||
|
) {
|
||||||
|
sealed class Incompatibility {
|
||||||
|
object MinSdk : Incompatibility()
|
||||||
|
object MaxSdk : Incompatibility()
|
||||||
|
object Platform : Incompatibility()
|
||||||
|
class Feature(val feature: String) : Incompatibility()
|
||||||
|
}
|
||||||
|
|
||||||
|
val identifier: String
|
||||||
|
get() = "$versionCode.$hash"
|
||||||
|
|
||||||
|
fun getDownloadUrl(repository: Repository): String {
|
||||||
|
return Uri.parse(repository.address).buildUpon().appendPath(release).build().toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
val cacheFileName: String
|
||||||
|
get() = "${hash.replace('/', '-')}.apk"
|
||||||
|
}
|
||||||
417
app/src/main/kotlin/com/looker/droidify/model/Repository.kt
Normal file
417
app/src/main/kotlin/com/looker/droidify/model/Repository.kt
Normal file
@@ -0,0 +1,417 @@
|
|||||||
|
package com.looker.droidify.model
|
||||||
|
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
data class Repository(
|
||||||
|
var id: Long,
|
||||||
|
val address: String,
|
||||||
|
val mirrors: List<String>,
|
||||||
|
val name: String,
|
||||||
|
val description: String,
|
||||||
|
val version: Int,
|
||||||
|
val enabled: Boolean,
|
||||||
|
val fingerprint: String,
|
||||||
|
val lastModified: String,
|
||||||
|
val entityTag: String,
|
||||||
|
val updated: Long,
|
||||||
|
val timestamp: Long,
|
||||||
|
val authentication: String,
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun edit(address: String, fingerprint: String, authentication: String): Repository {
|
||||||
|
val isAddressChanged = this.address != address
|
||||||
|
val isFingerprintChanged = this.fingerprint != fingerprint
|
||||||
|
val shouldForceUpdate = isAddressChanged || isFingerprintChanged
|
||||||
|
return copy(
|
||||||
|
address = address,
|
||||||
|
fingerprint = fingerprint,
|
||||||
|
lastModified = if (shouldForceUpdate) "" else lastModified,
|
||||||
|
entityTag = if (shouldForceUpdate) "" else entityTag,
|
||||||
|
authentication = authentication
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun update(
|
||||||
|
mirrors: List<String>,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
version: Int,
|
||||||
|
lastModified: String,
|
||||||
|
entityTag: String,
|
||||||
|
timestamp: Long,
|
||||||
|
): Repository {
|
||||||
|
return copy(
|
||||||
|
mirrors = mirrors,
|
||||||
|
name = name,
|
||||||
|
description = description,
|
||||||
|
version = if (version >= 0) version else this.version,
|
||||||
|
lastModified = lastModified,
|
||||||
|
entityTag = entityTag,
|
||||||
|
updated = System.currentTimeMillis(),
|
||||||
|
timestamp = timestamp
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun enable(enabled: Boolean): Repository {
|
||||||
|
return copy(enabled = enabled, lastModified = "", entityTag = "")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("SpellCheckingInspection")
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
fun newRepository(
|
||||||
|
address: String,
|
||||||
|
fingerprint: String,
|
||||||
|
authentication: String,
|
||||||
|
): Repository {
|
||||||
|
val name = try {
|
||||||
|
URL(address).let { "${it.host}${it.path}" }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
address
|
||||||
|
}
|
||||||
|
return defaultRepository(address, name, "", 0, true, fingerprint, authentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun defaultRepository(
|
||||||
|
address: String,
|
||||||
|
name: String,
|
||||||
|
description: String,
|
||||||
|
version: Int = 21,
|
||||||
|
enabled: Boolean = false,
|
||||||
|
fingerprint: String,
|
||||||
|
authentication: String = "",
|
||||||
|
): Repository {
|
||||||
|
return Repository(
|
||||||
|
-1, address, emptyList(), name, description, version, enabled,
|
||||||
|
fingerprint, "", "", 0L, 0L, authentication
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val defaultRepositories = listOf(
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://f-droid.org/repo",
|
||||||
|
name = "F-Droid",
|
||||||
|
description = "The official F-Droid Free Software repos" +
|
||||||
|
"itory. Everything in this repository is always buil" +
|
||||||
|
"t from the source code.",
|
||||||
|
enabled = true,
|
||||||
|
fingerprint = "43238D512C1E5EB2D6569F4A3AFBF5523418B82E0A3ED1552770ABB9A9C9CCAB"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://f-droid.org/archive",
|
||||||
|
name = "F-Droid Archive",
|
||||||
|
description = "The archive of the official F-Droid Free" +
|
||||||
|
" Software repository. Apps here are old and can co" +
|
||||||
|
"ntain known vulnerabilities and security issues!",
|
||||||
|
fingerprint = "43238D512C1E5EB2D6569F4A3AFBF5523418B82E0A3ED1552770ABB9A9C9CCAB"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://guardianproject.info/fdroid/repo",
|
||||||
|
name = "Guardian Project Official Releases",
|
||||||
|
description = "The official repository of The Guardian " +
|
||||||
|
"Project apps for use with the F-Droid client. Appl" +
|
||||||
|
"ications in this repository are official binaries " +
|
||||||
|
"built by the original application developers and " +
|
||||||
|
"signed by the same key as the APKs that are relea" +
|
||||||
|
"sed in the Google Play Store.",
|
||||||
|
fingerprint = "B7C2EEFD8DAC7806AF67DFCD92EB18126BC08312A7F2D6F3862E46013C7A6135"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://guardianproject.info/fdroid/archive",
|
||||||
|
name = "Guardian Project Archive",
|
||||||
|
description = "The official repository of The Guardian Pr" +
|
||||||
|
"oject apps for use with the F-Droid client. This con" +
|
||||||
|
"tains older versions of applications from the main repository.",
|
||||||
|
fingerprint = "B7C2EEFD8DAC7806AF67DFCD92EB18126BC08312A7F2D6F3862E46013C7A6135"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://apt.izzysoft.de/fdroid/repo",
|
||||||
|
name = "IzzyOnDroid F-Droid Repo",
|
||||||
|
description = "This is a repository of apps to be used with" +
|
||||||
|
" F-Droid the original application developers, taken" +
|
||||||
|
" from the resp. repositories (mostly GitHub). At thi" +
|
||||||
|
"s moment I cannot give guarantees on regular updates" +
|
||||||
|
" for all of them, though most are checked multiple times a week ",
|
||||||
|
enabled = true,
|
||||||
|
fingerprint = "3BF0D6ABFEAE2F401707B6D966BE743BF0EEE49C2561B9BA39073711F628937A"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://microg.org/fdroid/repo",
|
||||||
|
name = "MicroG Project",
|
||||||
|
description = "The official repository for MicroG." +
|
||||||
|
" MicroG is a lightweight open-source implementation" +
|
||||||
|
" of Google Play Services.",
|
||||||
|
fingerprint = "9BD06727E62796C0130EB6DAB39B73157451582CBD138E86C468ACC395D14165"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://repo.netsyms.com/fdroid/repo",
|
||||||
|
name = "Netsyms Technologies",
|
||||||
|
description = "Official collection of open-source apps created" +
|
||||||
|
" by Netsyms Technologies.",
|
||||||
|
fingerprint = "2581BA7B32D3AB443180C4087CAB6A7E8FB258D3A6E98870ECB3C675E4D64489"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://molly.im/fdroid/foss/fdroid/repo",
|
||||||
|
name = "Molly",
|
||||||
|
description = "The official repository for Molly. " +
|
||||||
|
"Molly is a fork of Signal focused on security.",
|
||||||
|
fingerprint = "5198DAEF37FC23C14D5EE32305B2AF45787BD7DF2034DE33AD302BDB3446DF74"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://archive.newpipe.net/fdroid/repo",
|
||||||
|
name = "NewPipe",
|
||||||
|
description = "The official repository for NewPipe." +
|
||||||
|
" NewPipe is a lightweight client for Youtube, PeerTube" +
|
||||||
|
", Soundcloud, etc.",
|
||||||
|
fingerprint = "E2402C78F9B97C6C89E97DB914A2751FDA1D02FE2039CC0897A462BDB57E7501"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://www.collaboraoffice.com/downloads/fdroid/repo",
|
||||||
|
name = "Collabora Office",
|
||||||
|
description = "Collabora Office is an office suite based on LibreOffice.",
|
||||||
|
fingerprint = "573258C84E149B5F4D9299E7434B2B69A8410372921D4AE586BA91EC767892CC"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.libretro.com/repo",
|
||||||
|
name = "LibRetro",
|
||||||
|
description = "The official canary repository for this great" +
|
||||||
|
" retro emulators hub.",
|
||||||
|
fingerprint = "3F05B24D497515F31FEAB421297C79B19552C5C81186B3750B7C131EF41D733D"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://cdn.kde.org/android/fdroid/repo",
|
||||||
|
name = "KDE Android",
|
||||||
|
description = "The official nightly repository for KDE Android apps.",
|
||||||
|
fingerprint = "B3EBE10AFA6C5C400379B34473E843D686C61AE6AD33F423C98AF903F056523F"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://calyxos.gitlab.io/calyx-fdroid-repo/fdroid/repo",
|
||||||
|
name = "Calyx OS Repo",
|
||||||
|
description = "The official Calyx Labs F-Droid repository.",
|
||||||
|
fingerprint = "C44D58B4547DE5096138CB0B34A1CC99DAB3B4274412ED753FCCBFC11DC1B7B6"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://divestos.org/fdroid/official",
|
||||||
|
name = "Divest OS Repo",
|
||||||
|
description = "The official Divest OS F-Droid repository.",
|
||||||
|
fingerprint = "E4BE8D6ABFA4D9D4FEEF03CDDA7FF62A73FD64B75566F6DD4E5E577550BE8467"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.fedilab.app/repo",
|
||||||
|
name = "Fedilab",
|
||||||
|
description = "The official repository for Fedilab. Fedilab is a " +
|
||||||
|
"multi-accounts client for Mastodon, Peertube, and other free" +
|
||||||
|
" software social networks.",
|
||||||
|
fingerprint = "11F0A69910A4280E2CD3CCC3146337D006BE539B18E1A9FEACE15FF757A94FEB"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://store.nethunter.com/repo",
|
||||||
|
name = "Kali Nethunter",
|
||||||
|
description = "Kali Nethunter's official selection of original b" +
|
||||||
|
"inaries.",
|
||||||
|
fingerprint = "7E418D34C3AD4F3C37D7E6B0FACE13332364459C862134EB099A3BDA2CCF4494"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://secfirst.org/fdroid/repo",
|
||||||
|
name = "Umbrella",
|
||||||
|
description = "The official repository for Umbrella. Umbrella is" +
|
||||||
|
" a collection of security advices, tutorials, tools etc.",
|
||||||
|
fingerprint = "39EB57052F8D684514176819D1645F6A0A7BD943DBC31AB101949006AC0BC228"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://thecapslock.gitlab.io/fdroid-patched-apps/fdroid/repo",
|
||||||
|
name = "Patched Apps",
|
||||||
|
description = "A collection of patched applications to provid" +
|
||||||
|
"e better compatibility, privacy etc..",
|
||||||
|
fingerprint = "313D9E6E789FF4E8E2D687AAE31EEF576050003ED67963301821AC6D3763E3AC"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://mobileapp.bitwarden.com/fdroid/repo",
|
||||||
|
name = "Bitwarden",
|
||||||
|
description = "The official repository for Bitwarden. Bitward" +
|
||||||
|
"en is a password manager.",
|
||||||
|
fingerprint = "BC54EA6FD1CD5175BCCCC47C561C5726E1C3ED7E686B6DB4B18BAC843A3EFE6C"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://briarproject.org/fdroid/repo",
|
||||||
|
name = "Briar",
|
||||||
|
description = "The official repository for Briar. Briar is a" +
|
||||||
|
" serverless/offline messenger that focused on privacy, s" +
|
||||||
|
"ecurity, and decentralization.",
|
||||||
|
fingerprint = "1FB874BEE7276D28ECB2C9B06E8A122EC4BCB4008161436CE474C257CBF49BD6"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://guardianproject-wind.s3.amazonaws.com/fdroid/repo",
|
||||||
|
name = "Wind Project",
|
||||||
|
description = "A collection of interesting offline/serverless apps.",
|
||||||
|
fingerprint = "182CF464D219D340DA443C62155198E399FEC1BC4379309B775DD9FC97ED97E1"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://nanolx.org/fdroid/repo",
|
||||||
|
name = "NanoDroid",
|
||||||
|
description = "A companion repository to microG's installer.",
|
||||||
|
fingerprint = "862ED9F13A3981432BF86FE93D14596B381D75BE83A1D616E2D44A12654AD015"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://releases.threema.ch/fdroid/repo",
|
||||||
|
name = "Threema Libre",
|
||||||
|
description = "The official repository for Threema Libre. R" +
|
||||||
|
"equires Threema Shop license. Threema Libre is an open" +
|
||||||
|
"-source messanger focused on security and privacy.",
|
||||||
|
fingerprint = "5734E753899B25775D90FE85362A49866E05AC4F83C05BEF5A92880D2910639E"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.getsession.org/fdroid/repo",
|
||||||
|
name = "Session",
|
||||||
|
description = "The official repository for Session. Session" +
|
||||||
|
" is an open-source messanger focused on security and privacy.",
|
||||||
|
fingerprint = "DB0E5297EB65CC22D6BD93C869943BDCFCB6A07DC69A48A0DD8C7BA698EC04E6"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://www.cromite.org/fdroid/repo",
|
||||||
|
name = "Cromite",
|
||||||
|
description = "The official repository for Cromite. Cromite" +
|
||||||
|
" is a Chromium with ad blocking and enhanced privacy.",
|
||||||
|
fingerprint = "49F37E74DEE483DCA2B991334FB5A0200787430D0B5F9A783DD5F13695E9517B"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.twinhelix.com/fdroid/repo",
|
||||||
|
name = "TwinHelix",
|
||||||
|
description = "TwinHelix F-Droid Repository, used for Signa" +
|
||||||
|
"l-FOSS, an open-source fork of Signal Private Messenger.",
|
||||||
|
fingerprint = "7b03b0232209b21b10a30a63897d3c6bca4f58fe29bc3477e8e3d8cf8e304028"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.typeblog.net",
|
||||||
|
name = "PeterCxy's F-Droid",
|
||||||
|
description = "You have landed on PeterCxy's F-Droid repo. T" +
|
||||||
|
"o use this repository, please add the page's URL to your F-Droid client.",
|
||||||
|
fingerprint = "1a7e446c491c80bc2f83844a26387887990f97f2f379ae7b109679feae3dbc8c"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://s2.spiritcroc.de/fdroid/repo",
|
||||||
|
name = "SpiritCroc.de",
|
||||||
|
description = "While some of my apps are available from" +
|
||||||
|
" the official F-Droid repository, I also maintain my" +
|
||||||
|
" own repository for a small selection of apps. These" +
|
||||||
|
" might be forks of other apps with only minor change" +
|
||||||
|
"s, or apps that are not published on the Play Store f" +
|
||||||
|
"or other reasons. In contrast to the official F-Droid" +
|
||||||
|
" repos, these might also include proprietary librarie" +
|
||||||
|
"s, e.g. for push notifications.",
|
||||||
|
fingerprint = "6612ade7e93174a589cf5ba26ed3ab28231a789640546c8f30375ef045bc9242"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://s2.spiritcroc.de/testing/fdroid/repo",
|
||||||
|
name = "SpiritCroc.de Test Builds",
|
||||||
|
description = "SpiritCroc.de Test Builds",
|
||||||
|
fingerprint = "52d03f2fab785573bb295c7ab270695e3a1bdd2adc6a6de8713250b33f231225"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://static.cryptomator.org/android/fdroid/repo",
|
||||||
|
name = "Cryptomator",
|
||||||
|
description = "No Description",
|
||||||
|
fingerprint = "f7c3ec3b0d588d3cb52983e9eb1a7421c93d4339a286398e71d7b651e8d8ecdd"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://divestos.org/apks/unofficial/fdroid/repo",
|
||||||
|
name = "DivestOS Unofficial",
|
||||||
|
description = "This repository contains unofficial builds of open source apps" +
|
||||||
|
" that are not included in the other repos.",
|
||||||
|
fingerprint = "a18cdb92f40ebfbbf778a54fd12dbd74d90f1490cb9ef2cc6c7e682dd556855d"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://cdn.kde.org/android/stable-releases/fdroid/repo",
|
||||||
|
name = "KDE Stables",
|
||||||
|
description = "This repository contains unofficial builds of open source apps" +
|
||||||
|
" that are not included in the other repos.",
|
||||||
|
fingerprint = "13784ba6c80ff4e2181e55c56f961eed5844cea16870d3b38d58780b85e1158f"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://zimbelstern.eu/fdroid/repo",
|
||||||
|
name = "Zimbelstern's F-Droid repository",
|
||||||
|
description = "This is the official repository of apps from zimbelstern.eu," +
|
||||||
|
" to be used with F-Droid.",
|
||||||
|
fingerprint = "285158DECEF37CB8DE7C5AF14818ACBF4A9B1FBE63116758EFC267F971CA23AA"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://app.simplex.chat/fdroid/repo",
|
||||||
|
name = "SimpleX Chat F-Droid",
|
||||||
|
description = "SimpleX Chat official F-Droid repository.",
|
||||||
|
fingerprint = "9F358FF284D1F71656A2BFAF0E005DEAE6AA14143720E089F11FF2DDCFEB01BA"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://f-droid.monerujo.io/fdroid/repo",
|
||||||
|
name = "Monerujo Wallet",
|
||||||
|
description = "Monerujo Monero Wallet official F-Droid repository.",
|
||||||
|
fingerprint = "A82C68E14AF0AA6A2EC20E6B272EFF25E5A038F3F65884316E0F5E0D91E7B713"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.cakelabs.com/fdroid/repo",
|
||||||
|
name = "Cake Labs",
|
||||||
|
description = "Cake Labs official F-Droid repository for Cake Wallet and Monero.com",
|
||||||
|
fingerprint = "EA44EFAEE0B641EE7A032D397D5D976F9C4E5E1ED26E11C75702D064E55F8755"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://app.futo.org/fdroid/repo",
|
||||||
|
name = "FUTO",
|
||||||
|
description = "FUTO official F-Droid repository.",
|
||||||
|
fingerprint = "39D47869D29CBFCE4691D9F7E6946A7B6D7E6FF4883497E6E675744ECDFA6D6D"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.mm20.de/repo",
|
||||||
|
name = "MM20 Apps",
|
||||||
|
description = "Apps developed and distributed by MM20",
|
||||||
|
fingerprint = "156FBAB952F6996415F198F3F29628D24B30E725B0F07A2B49C3A9B5161EEE1A"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://breezy-weather.github.io/fdroid-repo/fdroid/repo",
|
||||||
|
name = "Breezy Weather",
|
||||||
|
description = "The F-Droid repository for Breezy Weather",
|
||||||
|
fingerprint = "3480A7BB2A296D8F98CB90D2309199B5B9519C1B31978DBCD877ADB102AF35EE"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://gh.artemchep.com/keyguard-repo-fdroid/repo",
|
||||||
|
name = "Keyguard Project",
|
||||||
|
description = "Mirrors artifacts available on https://github.com/AChep/keyguard-app/releases",
|
||||||
|
fingerprint = "03941CE79B081666609C8A48AB6E46774263F6FC0BBF1FA046CCFFC60EA643BC"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://f5a.torus.icu/fdroid/repo",
|
||||||
|
name = "Fcitx 5 For Android F-Droid Repo",
|
||||||
|
description = "Out-of-tree fcitx5-android plugins.",
|
||||||
|
fingerprint = "5D87CE1FAD3772425C2A7ED987A57595A20B07543B9595A7FD2CED25DFF3CF12"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.i2pd.xyz/fdroid/repo/",
|
||||||
|
name = "PurpleI2P F-Droid repository",
|
||||||
|
description = "This is a repository of PurpleI2P. It contains applications developed and supported by our team.",
|
||||||
|
fingerprint = "5D87CE1FAD3772425C2A7ED987A57595A20B07543B9595A7FD2CED25DFF3CF12"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
val newlyAdded: List<Repository> = listOf(
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://fdroid.ironfoxoss.org/fdroid/repo",
|
||||||
|
name = "IronFox",
|
||||||
|
description = "The official repository for IronFox:" +
|
||||||
|
" A privacy and security-oriented Firefox-based browser for Android.",
|
||||||
|
fingerprint = "C5E291B5A571F9C8CD9A9799C2C94E02EC9703948893F2CA756D67B94204F904"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://raw.githubusercontent.com/chrisgch/tca/master/fdroid/repo",
|
||||||
|
name = "Total Commander",
|
||||||
|
description = "The official repository for Total Commander",
|
||||||
|
fingerprint = "3576596CECDD70488D61CFD90799A49B7FFD26A81A8FEF1BADEC88D069FA72C1"
|
||||||
|
),
|
||||||
|
defaultRepository(
|
||||||
|
address = "https://www.cromite.org/fdroid/repo",
|
||||||
|
name = "Cromite",
|
||||||
|
description = "The official repository for Cromite. " +
|
||||||
|
"Cromite is a Chromium fork based on Bromite with " +
|
||||||
|
"built-in support for ad blocking and an eye for privacy.",
|
||||||
|
fingerprint = "49F37E74DEE483DCA2B991334FB5A0200787430D0B5F9A783DD5F13695E9517B"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
30
app/src/main/kotlin/com/looker/droidify/network/DataSize.kt
Normal file
30
app/src/main/kotlin/com/looker/droidify/network/DataSize.kt
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package com.looker.droidify.network
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
@JvmInline
|
||||||
|
value class DataSize(val value: Long) {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val BYTE_SIZE = 1024L
|
||||||
|
private val sizeFormats = listOf("%.0f B", "%.0f kB", "%.1f MB", "%.2f GB")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
val (size, index) = generateSequence(Pair(value.toFloat(), 0)) { (size, index) ->
|
||||||
|
if (size >= BYTE_SIZE) {
|
||||||
|
Pair(size / BYTE_SIZE, index + 1)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}.take(sizeFormats.size).last()
|
||||||
|
return sizeFormats[index].format(Locale.US, size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
infix fun DataSize.percentBy(denominator: DataSize?): Int = value percentBy denominator?.value
|
||||||
|
|
||||||
|
infix fun Long.percentBy(denominator: Long?): Int {
|
||||||
|
if (denominator == null || denominator < 1) return -1
|
||||||
|
return (this * 100 / denominator).toInt()
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package com.looker.droidify.network
|
||||||
|
|
||||||
|
import com.looker.droidify.network.header.HeadersBuilder
|
||||||
|
import com.looker.droidify.network.validation.FileValidator
|
||||||
|
import java.io.File
|
||||||
|
import java.net.Proxy
|
||||||
|
|
||||||
|
interface Downloader {
|
||||||
|
|
||||||
|
fun setProxy(proxy: Proxy)
|
||||||
|
|
||||||
|
suspend fun headCall(
|
||||||
|
url: String,
|
||||||
|
headers: HeadersBuilder.() -> Unit = {}
|
||||||
|
): NetworkResponse
|
||||||
|
|
||||||
|
suspend fun downloadToFile(
|
||||||
|
url: String,
|
||||||
|
target: File,
|
||||||
|
validator: FileValidator? = null,
|
||||||
|
headers: HeadersBuilder.() -> Unit = {},
|
||||||
|
block: ProgressListener? = null
|
||||||
|
): NetworkResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
typealias ProgressListener = suspend (bytesReceived: DataSize, contentLength: DataSize) -> Unit
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package com.looker.droidify.network
|
||||||
|
|
||||||
|
import com.looker.droidify.BuildConfig
|
||||||
|
import com.looker.droidify.network.header.HeadersBuilder
|
||||||
|
import com.looker.droidify.network.header.KtorHeadersBuilder
|
||||||
|
import com.looker.droidify.network.validation.FileValidator
|
||||||
|
import com.looker.droidify.network.validation.ValidationException
|
||||||
|
import com.looker.droidify.utility.common.extension.size
|
||||||
|
import io.ktor.client.HttpClient
|
||||||
|
import io.ktor.client.HttpClientConfig
|
||||||
|
import io.ktor.client.engine.HttpClientEngine
|
||||||
|
import io.ktor.client.engine.okhttp.OkHttp
|
||||||
|
import io.ktor.client.network.sockets.ConnectTimeoutException
|
||||||
|
import io.ktor.client.network.sockets.SocketTimeoutException
|
||||||
|
import io.ktor.client.plugins.HttpTimeout
|
||||||
|
import io.ktor.client.plugins.UserAgent
|
||||||
|
import io.ktor.client.plugins.onDownload
|
||||||
|
import io.ktor.client.request.head
|
||||||
|
import io.ktor.client.request.headers
|
||||||
|
import io.ktor.client.request.prepareGet
|
||||||
|
import io.ktor.client.request.request
|
||||||
|
import io.ktor.client.request.url
|
||||||
|
import io.ktor.client.statement.HttpResponse
|
||||||
|
import io.ktor.client.statement.bodyAsChannel
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.http.etag
|
||||||
|
import io.ktor.http.isSuccess
|
||||||
|
import io.ktor.http.lastModified
|
||||||
|
import io.ktor.utils.io.jvm.javaio.copyTo
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.IOException
|
||||||
|
import java.net.Proxy
|
||||||
|
import kotlin.coroutines.cancellation.CancellationException
|
||||||
|
|
||||||
|
internal class KtorDownloader(
|
||||||
|
httpClientEngine: HttpClientEngine,
|
||||||
|
private val dispatcher: CoroutineDispatcher,
|
||||||
|
) : Downloader {
|
||||||
|
|
||||||
|
private var client = client(httpClientEngine)
|
||||||
|
set(newClient) {
|
||||||
|
field.close()
|
||||||
|
field = newClient
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun setProxy(proxy: Proxy) {
|
||||||
|
client = client(OkHttp.create { this.proxy = proxy })
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun headCall(
|
||||||
|
url: String,
|
||||||
|
headers: HeadersBuilder.() -> Unit
|
||||||
|
): NetworkResponse {
|
||||||
|
val headRequest = createRequest(
|
||||||
|
url = url,
|
||||||
|
headers = headers
|
||||||
|
)
|
||||||
|
return client.head(headRequest).asNetworkResponse()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun downloadToFile(
|
||||||
|
url: String,
|
||||||
|
target: File,
|
||||||
|
validator: FileValidator?,
|
||||||
|
headers: HeadersBuilder.() -> Unit,
|
||||||
|
block: ProgressListener?
|
||||||
|
): NetworkResponse = withContext(dispatcher) {
|
||||||
|
try {
|
||||||
|
val request = createRequest(
|
||||||
|
url = url,
|
||||||
|
headers = {
|
||||||
|
inRange(target.size)
|
||||||
|
headers()
|
||||||
|
},
|
||||||
|
fileSize = target.size,
|
||||||
|
block = block
|
||||||
|
)
|
||||||
|
client.prepareGet(request).execute { response ->
|
||||||
|
val networkResponse = response.asNetworkResponse()
|
||||||
|
if (networkResponse !is NetworkResponse.Success) {
|
||||||
|
return@execute networkResponse
|
||||||
|
}
|
||||||
|
response.bodyAsChannel().copyTo(target.outputStream())
|
||||||
|
validator?.validate(target)
|
||||||
|
networkResponse
|
||||||
|
}
|
||||||
|
} catch (e: SocketTimeoutException) {
|
||||||
|
NetworkResponse.Error.SocketTimeout(e)
|
||||||
|
} catch (e: ConnectTimeoutException) {
|
||||||
|
NetworkResponse.Error.ConnectionTimeout(e)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
NetworkResponse.Error.IO(e)
|
||||||
|
} catch (e: ValidationException) {
|
||||||
|
target.delete()
|
||||||
|
NetworkResponse.Error.Validation(e)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
NetworkResponse.Error.Unknown(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun client(
|
||||||
|
engine: HttpClientEngine = OkHttp.create()
|
||||||
|
): HttpClient {
|
||||||
|
return HttpClient(engine) {
|
||||||
|
userAgentConfig()
|
||||||
|
timeoutConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private fun createRequest(
|
||||||
|
url: String,
|
||||||
|
headers: HeadersBuilder.() -> Unit,
|
||||||
|
fileSize: Long? = null,
|
||||||
|
block: ProgressListener? = null
|
||||||
|
) = request {
|
||||||
|
url(url)
|
||||||
|
this.headers {
|
||||||
|
KtorHeadersBuilder(this).headers()
|
||||||
|
}
|
||||||
|
onDownload { read, total ->
|
||||||
|
if (block != null) {
|
||||||
|
block(
|
||||||
|
DataSize(read + (fileSize ?: 0L)),
|
||||||
|
DataSize((total ?: 0L) + (fileSize ?: 0L))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val CONNECTION_TIMEOUT = 30_000L
|
||||||
|
private const val SOCKET_TIMEOUT = 15_000L
|
||||||
|
private const val USER_AGENT = "Droid-ify/${BuildConfig.VERSION_NAME}-${BuildConfig.BUILD_TYPE}"
|
||||||
|
|
||||||
|
private fun HttpClientConfig<*>.userAgentConfig() = install(UserAgent) {
|
||||||
|
agent = USER_AGENT
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun HttpClientConfig<*>.timeoutConfig() = install(HttpTimeout) {
|
||||||
|
connectTimeoutMillis = CONNECTION_TIMEOUT
|
||||||
|
socketTimeoutMillis = SOCKET_TIMEOUT
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun HttpResponse.asNetworkResponse(): NetworkResponse =
|
||||||
|
if (status.isSuccess() || status == HttpStatusCode.NotModified) {
|
||||||
|
NetworkResponse.Success(status.value, lastModified(), etag())
|
||||||
|
} else {
|
||||||
|
NetworkResponse.Error.Http(status.value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.looker.droidify.network
|
||||||
|
|
||||||
|
import com.looker.droidify.network.validation.ValidationException
|
||||||
|
import java.util.Date
|
||||||
|
|
||||||
|
sealed interface NetworkResponse {
|
||||||
|
|
||||||
|
sealed interface Error : NetworkResponse {
|
||||||
|
|
||||||
|
data class ConnectionTimeout(val exception: Exception) : Error
|
||||||
|
|
||||||
|
data class SocketTimeout(val exception: Exception) : Error
|
||||||
|
|
||||||
|
data class IO(val exception: Exception) : Error
|
||||||
|
|
||||||
|
data class Validation(val exception: ValidationException) : Error
|
||||||
|
|
||||||
|
data class Unknown(val exception: Exception) : Error
|
||||||
|
|
||||||
|
data class Http(val statusCode: Int) : Error
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Success(
|
||||||
|
val statusCode: Int,
|
||||||
|
val lastModified: Date?,
|
||||||
|
val etag: String?
|
||||||
|
) : NetworkResponse
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.looker.droidify.network.header
|
||||||
|
|
||||||
|
import java.util.Date
|
||||||
|
|
||||||
|
interface HeadersBuilder {
|
||||||
|
|
||||||
|
infix fun String.headsWith(value: Any?)
|
||||||
|
|
||||||
|
fun etag(etagString: String)
|
||||||
|
|
||||||
|
fun ifModifiedSince(date: Date)
|
||||||
|
|
||||||
|
fun ifModifiedSince(date: String)
|
||||||
|
|
||||||
|
fun authentication(username: String, password: String)
|
||||||
|
|
||||||
|
fun authentication(base64: String)
|
||||||
|
|
||||||
|
fun inRange(start: Number?, end: Number? = null)
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.looker.droidify.network.header
|
||||||
|
|
||||||
|
import io.ktor.http.HttpHeaders
|
||||||
|
import io.ktor.util.encodeBase64
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.TimeZone
|
||||||
|
|
||||||
|
internal class KtorHeadersBuilder(
|
||||||
|
private val builder: io.ktor.http.HeadersBuilder
|
||||||
|
) : HeadersBuilder {
|
||||||
|
|
||||||
|
override fun String.headsWith(value: Any?) {
|
||||||
|
if (value == null) return
|
||||||
|
with(builder) {
|
||||||
|
append(this@headsWith, value.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun etag(etagString: String) {
|
||||||
|
HttpHeaders.ETag headsWith etagString
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun ifModifiedSince(date: Date) {
|
||||||
|
HttpHeaders.IfModifiedSince headsWith date.toFormattedString()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun ifModifiedSince(date: String) {
|
||||||
|
HttpHeaders.IfModifiedSince headsWith date
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun authentication(username: String, password: String) {
|
||||||
|
HttpHeaders.Authorization headsWith "Basic ${"$username:$password".encodeBase64()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun authentication(base64: String) {
|
||||||
|
HttpHeaders.Authorization headsWith base64
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun inRange(start: Number?, end: Number?) {
|
||||||
|
if (start == null) return
|
||||||
|
val valueString = if (end != null) "bytes=$start-$end" else "bytes=$start-"
|
||||||
|
HttpHeaders.Range headsWith valueString
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
val HTTP_DATE_FORMAT: SimpleDateFormat
|
||||||
|
get() = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).apply {
|
||||||
|
timeZone = TimeZone.getTimeZone("GMT")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Date.toFormattedString(): String = HTTP_DATE_FORMAT.format(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.looker.droidify.network.validation
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
interface FileValidator {
|
||||||
|
|
||||||
|
@Throws(ValidationException::class)
|
||||||
|
suspend fun validate(file: File)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.looker.droidify.network.validation
|
||||||
|
|
||||||
|
class ValidationException(override val message: String) : Exception(message)
|
||||||
|
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
|
inline fun invalid(message: String): Nothing = throw ValidationException(message)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.looker.droidify.receivers
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import com.looker.droidify.utility.common.extension.getPackageInfoCompat
|
||||||
|
import com.looker.droidify.database.Database
|
||||||
|
import com.looker.droidify.utility.extension.toInstalledItem
|
||||||
|
|
||||||
|
class InstalledAppReceiver(private val packageManager: PackageManager) : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
val packageName =
|
||||||
|
intent.data?.let { if (it.scheme == "package") it.schemeSpecificPart else null }
|
||||||
|
if (packageName != null) {
|
||||||
|
when (intent.action.orEmpty()) {
|
||||||
|
Intent.ACTION_PACKAGE_ADDED,
|
||||||
|
Intent.ACTION_PACKAGE_REMOVED
|
||||||
|
-> {
|
||||||
|
val packageInfo = packageManager.getPackageInfoCompat(packageName)
|
||||||
|
if (packageInfo != null) {
|
||||||
|
Database.InstalledAdapter.put(packageInfo.toInstalledItem())
|
||||||
|
} else {
|
||||||
|
Database.InstalledAdapter.delete(packageName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package com.looker.droidify.service
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.ServiceConnection
|
||||||
|
import android.os.IBinder
|
||||||
|
|
||||||
|
class Connection<B : IBinder, S : ConnectionService<B>>(
|
||||||
|
private val serviceClass: Class<S>,
|
||||||
|
private val onBind: ((Connection<B, S>, B) -> Unit)? = null,
|
||||||
|
private val onUnbind: ((Connection<B, S>, B) -> Unit)? = null
|
||||||
|
) : ServiceConnection {
|
||||||
|
var binder: B? = null
|
||||||
|
private set
|
||||||
|
|
||||||
|
private fun handleUnbind() {
|
||||||
|
binder?.let {
|
||||||
|
binder = null
|
||||||
|
onUnbind?.invoke(this, it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServiceConnected(componentName: ComponentName, binder: IBinder) {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
binder as B
|
||||||
|
this.binder = binder
|
||||||
|
onBind?.invoke(this, binder)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServiceDisconnected(componentName: ComponentName) {
|
||||||
|
handleUnbind()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun bind(context: Context) {
|
||||||
|
context.bindService(Intent(context, serviceClass), this, Context.BIND_AUTO_CREATE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun unbind(context: Context) {
|
||||||
|
context.unbindService(this)
|
||||||
|
handleUnbind()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package com.looker.droidify.service
|
||||||
|
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
|
||||||
|
abstract class ConnectionService<T : IBinder> : Service() {
|
||||||
|
|
||||||
|
private val supervisorJob = SupervisorJob()
|
||||||
|
val lifecycleScope = CoroutineScope(Dispatchers.Main + supervisorJob)
|
||||||
|
|
||||||
|
abstract override fun onBind(intent: Intent): T
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
lifecycleScope.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,475 @@
|
|||||||
|
package com.looker.droidify.service
|
||||||
|
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import com.looker.droidify.BuildConfig
|
||||||
|
import com.looker.droidify.MainActivity
|
||||||
|
import com.looker.droidify.datastore.SettingsRepository
|
||||||
|
import com.looker.droidify.datastore.get
|
||||||
|
import com.looker.droidify.datastore.model.InstallerType
|
||||||
|
import com.looker.droidify.installer.InstallManager
|
||||||
|
import com.looker.droidify.installer.model.InstallState
|
||||||
|
import com.looker.droidify.installer.model.installFrom
|
||||||
|
import com.looker.droidify.installer.notification.createInstallNotification
|
||||||
|
import com.looker.droidify.installer.notification.installNotification
|
||||||
|
import com.looker.droidify.model.Release
|
||||||
|
import com.looker.droidify.model.Repository
|
||||||
|
import com.looker.droidify.network.DataSize
|
||||||
|
import com.looker.droidify.network.Downloader
|
||||||
|
import com.looker.droidify.network.NetworkResponse
|
||||||
|
import com.looker.droidify.network.percentBy
|
||||||
|
import com.looker.droidify.network.validation.ValidationException
|
||||||
|
import com.looker.droidify.utility.common.Constants
|
||||||
|
import com.looker.droidify.utility.common.Constants.NOTIFICATION_CHANNEL_INSTALL
|
||||||
|
import com.looker.droidify.utility.common.SdkCheck
|
||||||
|
import com.looker.droidify.utility.common.cache.Cache
|
||||||
|
import com.looker.droidify.utility.common.createNotificationChannel
|
||||||
|
import com.looker.droidify.utility.common.extension.notificationManager
|
||||||
|
import com.looker.droidify.utility.common.extension.startServiceCompat
|
||||||
|
import com.looker.droidify.utility.common.extension.stopForegroundCompat
|
||||||
|
import com.looker.droidify.utility.common.extension.toPendingIntent
|
||||||
|
import com.looker.droidify.utility.common.extension.updateAsMutable
|
||||||
|
import com.looker.droidify.utility.common.log
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import kotlinx.coroutines.flow.filter
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.flow.sample
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.yield
|
||||||
|
import java.io.File
|
||||||
|
import javax.inject.Inject
|
||||||
|
import com.looker.droidify.R.string as stringRes
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class DownloadService : ConnectionService<DownloadService.Binder>() {
|
||||||
|
companion object {
|
||||||
|
private const val ACTION_CANCEL = "${BuildConfig.APPLICATION_ID}.intent.action.CANCEL"
|
||||||
|
}
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var settingsRepository: SettingsRepository
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var downloader: Downloader
|
||||||
|
|
||||||
|
private val installerType
|
||||||
|
get() = settingsRepository.get { installerType }
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var installer: InstallManager
|
||||||
|
|
||||||
|
sealed class State(val packageName: String) {
|
||||||
|
data object Idle : State("")
|
||||||
|
data class Connecting(val name: String) : State(name)
|
||||||
|
data class Downloading(val name: String, val read: DataSize, val total: DataSize?) : State(
|
||||||
|
name
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Error(val name: String) : State(name)
|
||||||
|
data class Cancel(val name: String) : State(name)
|
||||||
|
data class Success(val name: String, val release: Release) : State(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
data class DownloadState(
|
||||||
|
val currentItem: State = State.Idle,
|
||||||
|
val queue: List<String> = emptyList()
|
||||||
|
) {
|
||||||
|
infix fun isDownloading(packageName: String): Boolean =
|
||||||
|
currentItem.packageName == packageName && (
|
||||||
|
currentItem is State.Connecting || currentItem is State.Downloading
|
||||||
|
)
|
||||||
|
|
||||||
|
infix fun isComplete(packageName: String): Boolean =
|
||||||
|
currentItem.packageName == packageName && (
|
||||||
|
currentItem is State.Error ||
|
||||||
|
currentItem is State.Cancel ||
|
||||||
|
currentItem is State.Success ||
|
||||||
|
currentItem is State.Idle
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val _downloadState = MutableStateFlow(DownloadState())
|
||||||
|
|
||||||
|
private class Task(
|
||||||
|
val packageName: String,
|
||||||
|
val name: String,
|
||||||
|
val release: Release,
|
||||||
|
val url: String,
|
||||||
|
val authentication: String,
|
||||||
|
val isUpdate: Boolean = false
|
||||||
|
) {
|
||||||
|
val notificationTag: String
|
||||||
|
get() = "download-$packageName"
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class CurrentTask(val task: Task, val job: Job, val lastState: State)
|
||||||
|
|
||||||
|
private var started = false
|
||||||
|
private val tasks = mutableListOf<Task>()
|
||||||
|
private var currentTask: CurrentTask? = null
|
||||||
|
|
||||||
|
private val lock = Mutex()
|
||||||
|
|
||||||
|
inner class Binder : android.os.Binder() {
|
||||||
|
val downloadState = _downloadState.asStateFlow()
|
||||||
|
fun enqueue(
|
||||||
|
packageName: String,
|
||||||
|
name: String,
|
||||||
|
repository: Repository,
|
||||||
|
release: Release,
|
||||||
|
isUpdate: Boolean = false
|
||||||
|
) {
|
||||||
|
val task = Task(
|
||||||
|
packageName = packageName,
|
||||||
|
name = name,
|
||||||
|
release = release,
|
||||||
|
url = release.getDownloadUrl(repository),
|
||||||
|
authentication = repository.authentication,
|
||||||
|
isUpdate = isUpdate
|
||||||
|
)
|
||||||
|
if (Cache.getReleaseFile(this@DownloadService, release.cacheFileName).exists()) {
|
||||||
|
lifecycleScope.launch { publishSuccess(task) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cancelTasks(packageName)
|
||||||
|
cancelCurrentTask(packageName)
|
||||||
|
notificationManager?.cancel(
|
||||||
|
task.notificationTag,
|
||||||
|
Constants.NOTIFICATION_ID_DOWNLOADING
|
||||||
|
)
|
||||||
|
tasks += task
|
||||||
|
if (currentTask == null) {
|
||||||
|
handleDownload()
|
||||||
|
} else {
|
||||||
|
updateCurrentQueue { add(packageName) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel(packageName: String) {
|
||||||
|
cancelTasks(packageName)
|
||||||
|
cancelCurrentTask(packageName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val binder = Binder()
|
||||||
|
override fun onBind(intent: Intent): Binder = binder
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
createNotificationChannel(
|
||||||
|
id = Constants.NOTIFICATION_CHANNEL_DOWNLOADING,
|
||||||
|
name = getString(stringRes.downloading),
|
||||||
|
)
|
||||||
|
createNotificationChannel(
|
||||||
|
id = NOTIFICATION_CHANNEL_INSTALL,
|
||||||
|
name = getString(stringRes.install)
|
||||||
|
)
|
||||||
|
|
||||||
|
lifecycleScope.launch {
|
||||||
|
_downloadState
|
||||||
|
.filter { currentTask != null }
|
||||||
|
.sample(400)
|
||||||
|
.collectLatest {
|
||||||
|
publishForegroundState(false, it.currentItem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onTimeout(startId: Int) {
|
||||||
|
super.onTimeout(startId)
|
||||||
|
onDestroy()
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
cancelTasks(null)
|
||||||
|
cancelCurrentTask(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
if (intent?.action == ACTION_CANCEL) {
|
||||||
|
currentTask?.let { binder.cancel(it.task.packageName) }
|
||||||
|
}
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelTasks(packageName: String?) {
|
||||||
|
tasks.removeAll {
|
||||||
|
(packageName == null || it.packageName == packageName) && run {
|
||||||
|
updateCurrentState(State.Cancel(it.packageName))
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelCurrentTask(packageName: String?) {
|
||||||
|
currentTask?.let {
|
||||||
|
if (packageName == null || it.task.packageName == packageName) {
|
||||||
|
it.job.cancel()
|
||||||
|
currentTask = null
|
||||||
|
updateCurrentState(State.Cancel(it.task.packageName))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed interface ErrorType {
|
||||||
|
data object IO : ErrorType
|
||||||
|
data object Http : ErrorType
|
||||||
|
data object SocketTimeout : ErrorType
|
||||||
|
data object ConnectionTimeout : ErrorType
|
||||||
|
class Validation(val exception: ValidationException) : ErrorType
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showNotificationError(task: Task, errorType: ErrorType) {
|
||||||
|
val intent = Intent(this, MainActivity::class.java)
|
||||||
|
.setAction(Intent.ACTION_VIEW)
|
||||||
|
.setData(Uri.parse("package:${task.packageName}"))
|
||||||
|
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||||
|
.toPendingIntent(this)
|
||||||
|
notificationManager?.notify(
|
||||||
|
task.notificationTag,
|
||||||
|
Constants.NOTIFICATION_ID_DOWNLOADING,
|
||||||
|
NotificationCompat
|
||||||
|
.Builder(this, Constants.NOTIFICATION_CHANNEL_DOWNLOADING)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_error)
|
||||||
|
.setColor(Color.GREEN)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setContentIntent(intent)
|
||||||
|
.errorNotificationContent(task, errorType)
|
||||||
|
.build()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun NotificationCompat.Builder.errorNotificationContent(
|
||||||
|
task: Task,
|
||||||
|
errorType: ErrorType
|
||||||
|
): NotificationCompat.Builder {
|
||||||
|
val title = if (errorType is ErrorType.Validation) {
|
||||||
|
stringRes.could_not_validate_FORMAT
|
||||||
|
} else {
|
||||||
|
stringRes.could_not_download_FORMAT
|
||||||
|
}
|
||||||
|
val description = when (errorType) {
|
||||||
|
ErrorType.ConnectionTimeout -> getString(stringRes.connection_error_DESC)
|
||||||
|
ErrorType.Http -> getString(stringRes.http_error_DESC)
|
||||||
|
ErrorType.IO -> getString(stringRes.io_error_DESC)
|
||||||
|
ErrorType.SocketTimeout -> getString(stringRes.socket_error_DESC)
|
||||||
|
is ErrorType.Validation -> errorType.exception.message
|
||||||
|
}
|
||||||
|
setContentTitle(getString(title, task.name))
|
||||||
|
return setContentText(description)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showNotificationInstall(task: Task) {
|
||||||
|
val intent = Intent(this, MainActivity::class.java)
|
||||||
|
.setAction(MainActivity.ACTION_INSTALL)
|
||||||
|
.setData(Uri.parse("package:${task.packageName}"))
|
||||||
|
.putExtra(MainActivity.EXTRA_CACHE_FILE_NAME, task.release.cacheFileName)
|
||||||
|
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||||
|
.toPendingIntent(this)
|
||||||
|
val notification = createInstallNotification(
|
||||||
|
appName = task.name,
|
||||||
|
state = InstallState.Pending,
|
||||||
|
autoCancel = true,
|
||||||
|
) {
|
||||||
|
setContentIntent(intent)
|
||||||
|
}
|
||||||
|
notificationManager?.installNotification(
|
||||||
|
packageName = task.packageName,
|
||||||
|
notification = notification,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun publishSuccess(task: Task) {
|
||||||
|
val currentInstaller = installerType.first()
|
||||||
|
updateCurrentQueue { add("") }
|
||||||
|
updateCurrentState(State.Success(task.packageName, task.release))
|
||||||
|
val autoInstallWithSessionInstaller =
|
||||||
|
SdkCheck.canAutoInstall(task.release.targetSdkVersion) &&
|
||||||
|
currentInstaller == InstallerType.SESSION &&
|
||||||
|
task.isUpdate
|
||||||
|
|
||||||
|
showNotificationInstall(task)
|
||||||
|
if (currentInstaller == InstallerType.ROOT ||
|
||||||
|
currentInstaller == InstallerType.SHIZUKU ||
|
||||||
|
autoInstallWithSessionInstaller
|
||||||
|
) {
|
||||||
|
val installItem = task.packageName installFrom task.release.cacheFileName
|
||||||
|
installer install installItem
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val stateNotificationBuilder by lazy {
|
||||||
|
NotificationCompat
|
||||||
|
.Builder(this, Constants.NOTIFICATION_CHANNEL_DOWNLOADING)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||||
|
.setColor(Color.GREEN)
|
||||||
|
.addAction(
|
||||||
|
0,
|
||||||
|
getString(stringRes.cancel),
|
||||||
|
PendingIntent.getService(
|
||||||
|
this,
|
||||||
|
0,
|
||||||
|
Intent(this, this::class.java).setAction(ACTION_CANCEL),
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publishForegroundState(force: Boolean, state: State) {
|
||||||
|
if (!force && currentTask == null) return
|
||||||
|
currentTask = currentTask!!.copy(lastState = state)
|
||||||
|
stateNotificationBuilder.downloadingNotificationContent(state)
|
||||||
|
?.let { notification ->
|
||||||
|
startForeground(
|
||||||
|
Constants.NOTIFICATION_ID_DOWNLOADING,
|
||||||
|
notification.build()
|
||||||
|
)
|
||||||
|
} ?: run {
|
||||||
|
log("Invalid Download State: $state", "DownloadService", Log.ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun NotificationCompat.Builder.downloadingNotificationContent(
|
||||||
|
state: State
|
||||||
|
): NotificationCompat.Builder? {
|
||||||
|
return when (state) {
|
||||||
|
is State.Connecting -> {
|
||||||
|
setContentTitle(getString(stringRes.downloading_FORMAT, currentTask!!.task.name))
|
||||||
|
setContentText(getString(stringRes.connecting))
|
||||||
|
setProgress(1, 0, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
is State.Downloading -> {
|
||||||
|
setContentTitle(getString(stringRes.downloading_FORMAT, currentTask!!.task.name))
|
||||||
|
if (state.total != null) {
|
||||||
|
setContentText("${state.read} / ${state.total}")
|
||||||
|
setProgress(100, state.read.value percentBy state.total.value, false)
|
||||||
|
} else {
|
||||||
|
setContentText(state.read.toString())
|
||||||
|
setProgress(0, 0, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleDownload() {
|
||||||
|
if (currentTask != null) return
|
||||||
|
if (tasks.isEmpty() && started) {
|
||||||
|
started = false
|
||||||
|
stopForegroundCompat()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!started) {
|
||||||
|
started = true
|
||||||
|
startServiceCompat()
|
||||||
|
}
|
||||||
|
val task = tasks.removeFirstOrNull() ?: return
|
||||||
|
with(stateNotificationBuilder) {
|
||||||
|
setWhen(System.currentTimeMillis())
|
||||||
|
setContentIntent(createNotificationIntent(task.packageName))
|
||||||
|
}
|
||||||
|
val connectionState = State.Connecting(task.packageName)
|
||||||
|
val partialReleaseFile =
|
||||||
|
Cache.getPartialReleaseFile(this, task.release.cacheFileName)
|
||||||
|
val job = lifecycleScope.downloadFile(task, partialReleaseFile)
|
||||||
|
currentTask = CurrentTask(task, job, connectionState)
|
||||||
|
publishForegroundState(true, connectionState)
|
||||||
|
updateCurrentState(State.Connecting(task.packageName))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotificationIntent(packageName: String): PendingIntent? =
|
||||||
|
Intent(this, MainActivity::class.java)
|
||||||
|
.setAction(Intent.ACTION_VIEW)
|
||||||
|
.setData(Uri.parse("package:$packageName"))
|
||||||
|
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
.toPendingIntent(this)
|
||||||
|
|
||||||
|
private fun CoroutineScope.downloadFile(
|
||||||
|
task: Task,
|
||||||
|
target: File
|
||||||
|
) = launch {
|
||||||
|
try {
|
||||||
|
val releaseValidator = ReleaseFileValidator(
|
||||||
|
context = this@DownloadService,
|
||||||
|
packageName = task.packageName,
|
||||||
|
release = task.release
|
||||||
|
)
|
||||||
|
val response = downloader.downloadToFile(
|
||||||
|
url = task.url,
|
||||||
|
target = target,
|
||||||
|
validator = releaseValidator,
|
||||||
|
headers = { authentication(task.authentication) }
|
||||||
|
) { read, total ->
|
||||||
|
yield()
|
||||||
|
updateCurrentState(State.Downloading(task.packageName, read, total))
|
||||||
|
}
|
||||||
|
|
||||||
|
when (response) {
|
||||||
|
is NetworkResponse.Success -> {
|
||||||
|
val releaseFile = Cache.getReleaseFile(
|
||||||
|
this@DownloadService,
|
||||||
|
task.release.cacheFileName
|
||||||
|
)
|
||||||
|
target.renameTo(releaseFile)
|
||||||
|
publishSuccess(task)
|
||||||
|
}
|
||||||
|
|
||||||
|
is NetworkResponse.Error -> {
|
||||||
|
updateCurrentState(State.Error(task.packageName))
|
||||||
|
val errorType = when (response) {
|
||||||
|
is NetworkResponse.Error.ConnectionTimeout -> ErrorType.ConnectionTimeout
|
||||||
|
is NetworkResponse.Error.IO -> ErrorType.IO
|
||||||
|
is NetworkResponse.Error.SocketTimeout -> ErrorType.SocketTimeout
|
||||||
|
is NetworkResponse.Error.Validation -> ErrorType.Validation(
|
||||||
|
response.exception
|
||||||
|
)
|
||||||
|
|
||||||
|
else -> ErrorType.Http
|
||||||
|
}
|
||||||
|
showNotificationError(task, errorType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
lock.withLock { currentTask = null }
|
||||||
|
handleDownload()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateCurrentState(state: State) {
|
||||||
|
_downloadState.update {
|
||||||
|
val newQueue =
|
||||||
|
if (state.packageName in it.queue) {
|
||||||
|
it.queue.updateAsMutable {
|
||||||
|
removeAll { name -> name == "" }
|
||||||
|
remove(state.packageName)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
it.queue
|
||||||
|
}
|
||||||
|
it.copy(currentItem = state, queue = newQueue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateCurrentQueue(block: MutableList<String>.() -> Unit) {
|
||||||
|
_downloadState.update { state ->
|
||||||
|
state.copy(queue = state.queue.updateAsMutable(block))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user