Compare commits
22 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
4b80c9648c | ||
![]() |
1667d0a8c9 | ||
![]() |
3f9a272c27 | ||
![]() |
51f1a50fef | ||
![]() |
12f6a91438 | ||
![]() |
c29f007050 | ||
![]() |
21c88e282f | ||
![]() |
cbc0c39ec2 | ||
![]() |
3a38c7cad2 | ||
![]() |
c53b2953e6 | ||
![]() |
2b9c9b5655 | ||
![]() |
dcf4a5868b | ||
![]() |
78e2847271 | ||
![]() |
62bbf06270 | ||
![]() |
c328443dbe | ||
![]() |
18cac3920d | ||
![]() |
8d600ee8ce | ||
![]() |
f59c455c2c | ||
![]() |
c88dcde311 | ||
![]() |
b5a63c303f | ||
![]() |
d491fc151a | ||
![]() |
41749c5ebb |
1
.gitattributes
vendored
@ -1 +0,0 @@
|
||||
*.gpg binary
|
3
.gitignore
vendored
@ -16,6 +16,7 @@ build.xml
|
||||
# Gradle files
|
||||
.gradle/
|
||||
build/
|
||||
gradle.properties
|
||||
|
||||
# Local configuration file (sdk path, etc)
|
||||
local.properties
|
||||
@ -45,5 +46,3 @@ junit-report.xml
|
||||
|
||||
# Screen dumps from Android Studio/DDMS
|
||||
captures/
|
||||
|
||||
/fdroid/
|
||||
|
197
.gitlab-ci.yml
@ -1,142 +1,83 @@
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
image: registry.gitlab.com/fdroid/ci-images-client:latest
|
||||
|
||||
.base:
|
||||
image: registry.gitlab.com/fdroid/ci-images-client:latest
|
||||
before_script:
|
||||
- export GRADLE_USER_HOME=$PWD/.gradle
|
||||
- export ANDROID_COMPILE_SDK=`sed -n 's,.*compileSdkVersion\s*\([0-9][0-9]*\).*,\1,p' app/build.gradle`
|
||||
- alias sdkmanager="sdkmanager --no_https"
|
||||
- echo y | sdkmanager "platforms;android-${ANDROID_COMPILE_SDK}" > /dev/null
|
||||
# limit RAM usage for all gradle runs
|
||||
- export maxmem=$(expr $(sed -n 's,^MemAvailable:[^0-9]*\([0-9][0-9]*\)[^0-9]*$,\1,p' /proc/meminfo) / 1024 / 2 / 1024 \* 1024)
|
||||
- printf "\norg.gradle.jvmargs=-Xmx${maxmem}m -XX:MaxPermSize=${maxmem}m\norg.gradle.daemon=false\norg.gradle.parallel=false\n" >> gradle.properties
|
||||
after_script:
|
||||
# this file changes every time but should not be cached
|
||||
- rm -f $GRADLE_USER_HOME/caches/modules-2/modules-2.lock
|
||||
- rm -fr $GRADLE_USER_HOME/caches/*/plugin-resolution/
|
||||
cache:
|
||||
cache:
|
||||
paths:
|
||||
- .gradle/wrapper
|
||||
- .gradle/caches
|
||||
|
||||
.test-template: &test-template
|
||||
extends: .base
|
||||
stage: test
|
||||
artifacts:
|
||||
name: "${CI_PROJECT_PATH}_${CI_JOB_STAGE}_${CI_COMMIT_REF_NAME}_${CI_COMMIT_SHA}"
|
||||
paths:
|
||||
- kernel.log
|
||||
- logcat.txt
|
||||
- app/core*
|
||||
- app/*.log
|
||||
- app/build/reports
|
||||
- app/build/outputs/*ml
|
||||
- app/build/outputs/apk
|
||||
expire_in: 1 week
|
||||
when: on_failure
|
||||
after_script:
|
||||
- echo "Download debug artifacts from https://gitlab.com/${CI_PROJECT_PATH}/-/jobs"
|
||||
before_script:
|
||||
- export GRADLE_USER_HOME=$PWD/.gradle
|
||||
- export ANDROID_COMPILE_SDK=`sed -n 's,.*compileSdkVersion\s*\([0-9][0-9]*\).*,\1,p' app/build.gradle`
|
||||
- echo y | android --silent update sdk --no-ui --filter android-${ANDROID_COMPILE_SDK}
|
||||
|
||||
# Run the most important first. Then we can decide whether to ignore
|
||||
# the style tests if the rest of the more meaningful tests pass.
|
||||
test_lint_pmd_checkstyle:
|
||||
<<: *test-template
|
||||
test:
|
||||
script:
|
||||
- export EXITVALUE=0
|
||||
- function set_error() { export EXITVALUE=1; printf "\x1b[31mERROR `history|tail -2|head -1|cut -b 6-500`\x1b[0m\n"; }
|
||||
- ./gradlew assemble
|
||||
- ./tools/check-format-strings.py
|
||||
- ./tools/remove-unused-and-blank-translations.py
|
||||
- echo "These are unused or blank translations that should be removed:"
|
||||
- git --no-pager diff --exit-code || export EXITVALUE=1
|
||||
- ./gradlew assemble -PdisablePreDex
|
||||
# always report on lint errors to the build log
|
||||
- sed -i -e 's,textReport .*,textReport true,' app/build.gradle
|
||||
- ./gradlew testFullDebugUnitTest || set_error
|
||||
- ./gradlew lint || set_error
|
||||
- ./gradlew pmd || set_error
|
||||
- ./gradlew checkstyle || set_error
|
||||
- ./tools/check-format-strings.py || set_error
|
||||
- ./tools/check-fastlane-whitespace.py || set_error
|
||||
- ./tools/remove-unused-and-blank-translations.py || set_error
|
||||
- echo "These are unused or blank translations that should be removed:"
|
||||
- git --no-pager diff --ignore-all-space --name-only --exit-code app/src/*/res/values*/strings.xml || set_error
|
||||
- ./gradlew lint -PdisablePreDex
|
||||
- ./gradlew pmd -PdisablePreDex
|
||||
- ./gradlew checkstyle -PdisablePreDex
|
||||
- ./gradlew test -PdisablePreDex || {
|
||||
for log in app/build/reports/*ests/*/*ml; do
|
||||
echo "read $log here:";
|
||||
(cat "$log" | curl --silent -F 'clbin=<-' https://clbin.com) || true;
|
||||
done;
|
||||
export EXITVALUE=1;
|
||||
}
|
||||
- exit $EXITVALUE
|
||||
|
||||
errorprone:
|
||||
extends: .base
|
||||
stage: test
|
||||
script:
|
||||
- apt-get update
|
||||
- apt-get install -t stretch-backports openjdk-11-jdk-headless
|
||||
- update-java-alternatives --set java-1.11.0-openjdk-amd64
|
||||
- export JAVA_HOME=/usr/lib/jvm/java-1.11.0-openjdk-amd64
|
||||
- cat config/errorprone.gradle >> app/build.gradle
|
||||
- ./gradlew -Dorg.gradle.dependency.verification=lenient assembleDebug
|
||||
|
||||
# Run the tests in the emulator. Each step is broken out to run on
|
||||
# its own since the CI runner can have limited RAM, and the emulator
|
||||
# can take a while to start.
|
||||
#
|
||||
# once these prove stable, the task should be switched to
|
||||
# connectedCheck to test all the build flavors
|
||||
.connected-template: &connected-template
|
||||
extends: .base
|
||||
script:
|
||||
- ./gradlew assembleFullDebug
|
||||
- export AVD_SDK=`echo $CI_JOB_NAME | awk '{print $2}'`
|
||||
- export AVD_TAG=`echo $CI_JOB_NAME | awk '{print $3}'`
|
||||
- export AVD_ARCH=`echo $CI_JOB_NAME | awk '{print $4}'`
|
||||
- export AVD_PACKAGE="system-images;android-${AVD_SDK};${AVD_TAG};${AVD_ARCH}"
|
||||
- echo $AVD_PACKAGE
|
||||
|
||||
- alias sdkmanager
|
||||
- ls -l ~/.android
|
||||
|
||||
- adb start-server
|
||||
- start-emulator
|
||||
- wait-for-emulator
|
||||
- adb devices
|
||||
- adb shell input keyevent 82 &
|
||||
- ./gradlew installFullDebug
|
||||
- adb shell am start -n org.fdroid.fdroid.debug/org.fdroid.fdroid.views.main.MainActivity
|
||||
- if [ $AVD_SDK -lt 25 ] || ! emulator -accel-check; then
|
||||
export FLAG=-Pandroid.testInstrumentationRunnerArguments.notAnnotation=androidx.test.filters.LargeTest;
|
||||
fi
|
||||
- ./gradlew connectedFullDebugAndroidTest $FLAG
|
||||
|
||||
no-accel 22 default x86:
|
||||
<<: *test-template
|
||||
<<: *connected-template
|
||||
|
||||
.kvm-template: &kvm-template
|
||||
tags:
|
||||
- fdroid
|
||||
- kvm
|
||||
only:
|
||||
connected10:
|
||||
variables:
|
||||
- $RUN_KVM_JOBS
|
||||
<<: *test-template
|
||||
<<: *connected-template
|
||||
|
||||
kvm 29 microg x86_64:
|
||||
<<: *kvm-template
|
||||
|
||||
deploy_nightly:
|
||||
extends: .base
|
||||
stage: deploy
|
||||
only:
|
||||
- master
|
||||
AVD_SDK: "10"
|
||||
script:
|
||||
- test -z "$DEBUG_KEYSTORE" && exit 0
|
||||
- sed -i
|
||||
's,<string name="app_name">.*</string>,<string name="app_name">F-Nightly</string>,'
|
||||
app/src/main/res/values*/strings.xml
|
||||
# add this nightly repo as a enabled repo
|
||||
- sed -i -e '/<\/string-array>/d' -e '/<\/resources>/d' app/src/main/res/values/default_repos.xml
|
||||
- echo "<item>${CI_PROJECT_PATH}-nightly</item>" >> app/src/main/res/values/default_repos.xml
|
||||
- echo "<item>${CI_PROJECT_URL}-nightly/raw/master/fdroid/repo</item>" >> app/src/main/res/values/default_repos.xml
|
||||
- cat config/nightly-repo/repo.xml >> app/src/main/res/values/default_repos.xml
|
||||
- export DB=`sed -n 's,.*DB_VERSION *= *\([0-9][0-9]*\).*,\1,p' app/src/main/java/org/fdroid/fdroid/data/DBHelper.java`
|
||||
- export versionCode=`printf '%d%05d' $DB $(date '+%s'| cut -b4-8)`
|
||||
- sed -i "s,^\(\s*versionCode\) *[0-9].*,\1 $versionCode," app/build.gradle
|
||||
# build the APKs!
|
||||
- ./gradlew assembleDebug
|
||||
- fdroid nightly -v
|
||||
- ./gradlew assembleDebug -PdisablePreDex
|
||||
- emulator64-arm -avd fcl-test-$AVD_SDK -no-skin -no-audio -no-window &
|
||||
- ./tools/wait-for-emulator
|
||||
- adb shell input keyevent 82 &
|
||||
- export EXITVALUE=0
|
||||
- ./gradlew connectedCheck -PdisablePreDex || {
|
||||
adb -e logcat -d '*:E';
|
||||
echo "get the full logcat here:";
|
||||
(adb -e logcat -d | curl --silent -F 'clbin=<-' https://clbin.com) || true;
|
||||
export EXITVALUE=1;
|
||||
}
|
||||
- for log in app/build/reports/*ests/*/*ml
|
||||
app/build/outputs/*results*/connected/*.xml; do
|
||||
echo "read $log here:";
|
||||
(cat "$log" | curl --silent -F 'clbin=<-' https://clbin.com) || true;
|
||||
done
|
||||
|
||||
connected24:
|
||||
variables:
|
||||
AVD_SDK: "24"
|
||||
script:
|
||||
- ./gradlew assembleDebug -PdisablePreDex
|
||||
- android list avd
|
||||
- emulator64-arm -avd fcl-test-$AVD_SDK -no-audio -no-window &
|
||||
- ./tools/wait-for-emulator
|
||||
- adb shell input keyevent 82 &
|
||||
- adb devices
|
||||
- export EXITVALUE=0
|
||||
- ./gradlew connectedCheck -PdisablePreDex || {
|
||||
adb -e logcat -d '*:E';
|
||||
echo "get the full logcat here:";
|
||||
(adb -e logcat -d | curl --silent -F 'clbin=<-' https://clbin.com) || true;
|
||||
export EXITVALUE=1;
|
||||
}
|
||||
- for log in app/build/reports/*ests/*/*ml
|
||||
app/build/outputs/*results*/connected/*.xml; do
|
||||
echo "read $log here:";
|
||||
(cat "$log" | curl --silent -F 'clbin=<-' https://clbin.com) || true;
|
||||
done
|
||||
- exit $EXITVALUE
|
||||
|
||||
after_script:
|
||||
# this file changes every time but should not be cached
|
||||
- rm -f $GRADLE_USER_HOME/caches/modules-2/modules-2.lock
|
||||
- rm -fr $GRADLE_USER_HOME/caches/*/plugin-resolution/
|
||||
|
3
.weblate
@ -1,3 +0,0 @@
|
||||
[weblate]
|
||||
url = https://hosted.weblate.org/api/
|
||||
translation = f-droid/f-droid
|
@ -10,7 +10,7 @@ fdroid_root := $(LOCAL_PATH)
|
||||
fdroid_dir := app
|
||||
fdroid_out := $(PWD)/$(OUT_DIR)/target/common/obj/APPS/$(LOCAL_MODULE)_intermediates
|
||||
fdroid_build := $(fdroid_root)/$(fdroid_dir)/build
|
||||
fdroid_apk := build/outputs/apk/full/release/$(fdroid_dir)-full-release-unsigned.apk
|
||||
fdroid_apk := build/outputs/apk/$(fdroid_dir)-release-unsigned.apk
|
||||
|
||||
$(fdroid_root)/$(fdroid_dir)/$(fdroid_apk):
|
||||
rm -Rf $(fdroid_build)
|
||||
|
574
CHANGELOG.md
@ -1,460 +1,20 @@
|
||||
### 1.13-alpha1 (2021-06-02)
|
||||
### 1.0.3 (2018-02-02)
|
||||
|
||||
* Stop repeated updates of Trichrome Library
|
||||
* set up "Android App Links" handling aka "Digital Asset Links"
|
||||
|
||||
* More changes to follow Material Design (@proletarius101)
|
||||
* fix background crash when APKs disappear from cache in process
|
||||
|
||||
* Improve OpenCollective badge (@ConnyDuck)
|
||||
* fix update notification crash on Android 2.3 (#1306)
|
||||
|
||||
### 1.13-alpha0 (2021-04-22)
|
||||
* reduce memory usage when checking APKs
|
||||
|
||||
* Theme support tied to built-in Android themes (@proletarius101)
|
||||
* limit WifiStateChangeService to 2 minute runs
|
||||
|
||||
* New top banner notifications: "No Internet" and "No Data or WiFi enabled"
|
||||
### 1.0.2 (2017-12-01)
|
||||
|
||||
* Improved handling of USB-OTG and SD Card repos and mirrors
|
||||
* fix crasher bug in Updates (#1203)
|
||||
|
||||
### 1.12.1 (2021-04-12)
|
||||
|
||||
* Fix trove4j verification error
|
||||
|
||||
### 1.12 (2021-04-06)
|
||||
|
||||
* Sync translations
|
||||
|
||||
### 1.12-alpha3 (2021-03-10)
|
||||
|
||||
* Opt-in F-Droid Metrics
|
||||
|
||||
### 1.12-alpha2 (2021-03-03)
|
||||
|
||||
* Overhaul clean up of cached files
|
||||
|
||||
* Support updating "shared library packages" like Trichrome (@uldiniad)
|
||||
|
||||
### 1.12-alpha1 (2021-02-25)
|
||||
|
||||
* Add extra sanitation to search terms to prevent vulnerabilities.
|
||||
|
||||
* Fix Nearby Swap's close button (@proletarius101)
|
||||
|
||||
* Bump to compileSdkVersion 29 to support Java8
|
||||
|
||||
* Set up WorkManager on demand to avoid slowing down starts
|
||||
|
||||
* Prefer system keys when APKs are signed by them (@glennmen)
|
||||
|
||||
### 1.12-alpha0 (2021-02-08)
|
||||
|
||||
* App description localization now fully respects lists of languages in Android
|
||||
Language Settings
|
||||
|
||||
* Latest Tab lists results based on the Language Settings
|
||||
|
||||
* Latest Tab now shows results ordered newest first (@TheLastProject @IzzySoft)
|
||||
|
||||
* Theme support modernized and tied to the built-in Android themes (@proletarius101)
|
||||
|
||||
* Search results greatly improved (@Tvax @gcbrown76)
|
||||
|
||||
* Let Android efficiently schedule background cache cleanup operations (@Isira-Seneviratne)
|
||||
|
||||
* Overhaul repo URL parsing for reliable repo adding (@projectgus)
|
||||
|
||||
### 1.11 (2020-12-29)
|
||||
|
||||
* Improved linkifying of URLs in app descriptions
|
||||
|
||||
* Improved handling of SDCards and USG-OTG in Nearby
|
||||
|
||||
* Modernized code and switched PNGs to vectors (thanks @isira-seneviratne!)
|
||||
|
||||
* Recognize longer repo URLs to support GitCDN/RawGit/etc mirrors
|
||||
|
||||
### 1.10 (2020-10-20)
|
||||
|
||||
* Improved language selection with multiple locales
|
||||
(thanks @spacecowboy and @bubu!)
|
||||
|
||||
### 1.10-alpha1 (2020-09-29)
|
||||
|
||||
* use notification channels for fine-grained control (@Isira-Seneviratne)
|
||||
|
||||
### 1.10-alpha0 (2020-07-20)
|
||||
|
||||
* Latest Tab will show better results on non-English devices
|
||||
|
||||
* updates to core libraries (Jackson, androidx, gradle, etc)
|
||||
|
||||
* use Gradle's new dependency verification
|
||||
|
||||
* polish whitelabeling support
|
||||
|
||||
### 1.9 (2020-06-25)
|
||||
|
||||
* Removed "Android App Link" support since it cannot work with
|
||||
F-Droid, and it was triggering DNS leaks.
|
||||
|
||||
* Archive Repos are now lower priority than the Repo (higher on the
|
||||
Manage Repos screen), fixing issues where it looked for icons,
|
||||
screenshots and other information in the Archive rather than the
|
||||
Repo itself.
|
||||
|
||||
* Fixed hopefully all occurrences where F-Droid client couldn't show an icon.
|
||||
The remaining cases of missing icons are now caused either by
|
||||
icons not included in upstream repo or by temporary network failures.
|
||||
(After updating this requires one additional repo update to take effect.)
|
||||
|
||||
* Fixed a problem where repository updates would never trigger
|
||||
when either "Over Data" or "Over Wifi" were disabled.
|
||||
|
||||
* Support OpenCollective donation option and highlight
|
||||
free software donation platforms
|
||||
|
||||
* Fix for when the app update button wasn't showing up or working
|
||||
in some cases (thanks @di72nn)
|
||||
|
||||
* Stop cropping feature header image (thanks @ByteHamster!)
|
||||
|
||||
* Make navigation bar match dark mode (thanks @MatthieuB!)
|
||||
|
||||
* Cleaned out obsolete code (thanks @Isira-Seneviratne!)
|
||||
|
||||
### 1.8-alpha2 (2020-02-04)
|
||||
|
||||
* stop showing Unknown Sources with Privileged Extension on Android 10 #1833
|
||||
|
||||
* add standard ripple effect to links on app details activity
|
||||
|
||||
* fix displaying default icon for apps without icons
|
||||
|
||||
### 1.8-alpha1 (2020-01-10)
|
||||
|
||||
* handle Android 10 permission config to stop Unknown Sources prompts
|
||||
|
||||
* keyboard opens when search is cleared
|
||||
|
||||
* translation sync with Android strings
|
||||
|
||||
* force common repo domains to HTTPS (GitLab, GitHub, Amazon)
|
||||
|
||||
### 1.8-alpha0 (2019-11-20)
|
||||
|
||||
* fix seekbar preference on recent Android versions (thanks @dkanada)
|
||||
|
||||
* handle API 29 split-permissions: fine location now implies coarse location
|
||||
|
||||
* define backup rules to avoid saving the swap repo
|
||||
|
||||
### 1.7.1 (2019-07-31)
|
||||
|
||||
* fix crashes from ACRA report emails
|
||||
|
||||
### 1.7 (2019-07-06)
|
||||
|
||||
* fix crash in Panic Settings
|
||||
|
||||
* catch random crashes related to WifiApControl
|
||||
|
||||
### 1.7-alpha2 (2019-06-18)
|
||||
|
||||
* USB OTG flash drives can be used as nearby repos and mirrors
|
||||
|
||||
### 1.7-alpha1 (2019-06-14)
|
||||
|
||||
* overhauled nearby swap using the device's hotspot AP
|
||||
|
||||
* add new panic responses: app uninstalls and reset repos to default
|
||||
|
||||
* fix proxy support on first start
|
||||
|
||||
### 1.7-alpha0 (2019-05-20)
|
||||
|
||||
* major refactor of "Nearby" UI code, to prepare for rewriting guts
|
||||
|
||||
* show "undo" after swiping away items from the Updates tab (thanks @Hocuri!)
|
||||
|
||||
* fix ETag handling when connecting to nginx mirrors #1737
|
||||
|
||||
* fix issues with "Latest" display caused by mishandling time zones #1757
|
||||
|
||||
* ignore all unimportant crashes in background services
|
||||
|
||||
* do not use Privileged Extension if it was disabled in Settings
|
||||
|
||||
### 1.6.2 (2019-05-20)
|
||||
|
||||
* fixed issue where cached indexes were wrongly redownloaded (#1737),
|
||||
thanks to @amiraliakbari for tracking it down!
|
||||
|
||||
* fixed wrong string for the translated title of the Updates Tab (#1785)
|
||||
|
||||
* fixed crashes on very low memory when starting
|
||||
|
||||
### 1.6.1 (2019-05-10)
|
||||
|
||||
* Updated translations
|
||||
|
||||
* fixed button size issues #1678
|
||||
|
||||
* stopped random background crashes
|
||||
|
||||
### 1.6 (2019-04-10)
|
||||
|
||||
* update F-Droid after all other updates (#1556)
|
||||
|
||||
* Improve adding repos from the clipboard (e.g. Firefox Klar)
|
||||
|
||||
* swap usability improvements
|
||||
|
||||
* many crash fixes in swap and background services
|
||||
|
||||
### 1.6-alpha2 (2019-03-28)
|
||||
|
||||
* Latest Tab now highlights apps that provide descriptions,
|
||||
translations, screenshots
|
||||
|
||||
* Auto-download from mirrors, to speed up downloads and reduce load on
|
||||
f-droid.org
|
||||
|
||||
* More efficient download caching (per-repo; across different
|
||||
webservers #1708)
|
||||
|
||||
* Fix problems canceling downloads (#1727, #1736, #1742)
|
||||
|
||||
* Fix downloading OBB files from repos (#1403)
|
||||
|
||||
### 1.6-alpha1 (2019-02-20)
|
||||
|
||||
* add switches in RepoDetails to disable any or all mirrors (#1696)
|
||||
|
||||
* choose random mirror for each package/APK download
|
||||
|
||||
* make all APK downloads be cached per-repo, not per-mirror
|
||||
|
||||
* handle Apache and Nginx ETags when checking if index is current (#1708)
|
||||
|
||||
### 1.6-alpha0 (2019-02-15)
|
||||
|
||||
* handle implied READ_EXTERNAL_STORAGE permissions, which trigger a
|
||||
permissions prompt on installs with Privileged Extension (#1702)
|
||||
|
||||
* sanitize index data to reduce the threats from the server
|
||||
|
||||
* set Read Timeout to trigger mirror use when reads are slow
|
||||
|
||||
* fix missing icons for those who do not use WiFi (#1592)
|
||||
|
||||
* use separate titles for Updates pref and Updates tab, so that they
|
||||
can be better translated
|
||||
|
||||
* UI fixes from @ConnyDuck (#1636, #1618)
|
||||
|
||||
### 1.5.1 (2019-01-07)
|
||||
|
||||
* Removed incomplete translations that were accidentally added in 1.5
|
||||
|
||||
* Fix screenshot background on dark themes (#1618)
|
||||
|
||||
### 1.5 (2018-12-26)
|
||||
|
||||
* Nearby swap bug fixes and improvements
|
||||
|
||||
* update language and translations about Nearby and swap
|
||||
|
||||
* Fix displaying of icons for self-built apps (#1108)
|
||||
|
||||
### 1.5-alpha2 (2018-12-21)
|
||||
|
||||
* support swapping via SD Cards
|
||||
|
||||
* display versionCode in expanded Versions list entries in Expert Mode
|
||||
|
||||
### 1.5-alpha1 (2018-12-12)
|
||||
|
||||
* UX and language cleanup of App Details
|
||||
|
||||
### 1.5-alpha0 (2018-10-19)
|
||||
|
||||
* add repos via additional_repos.xml from ROM, OEM, Vendor.
|
||||
|
||||
### 1.4 (2018-09-12)
|
||||
|
||||
* polish up new "Versions" list and other UI fixes
|
||||
|
||||
### 1.4-alpha1 (2018-08-30)
|
||||
|
||||
* huge overhaul of the "Versions" list in the App Details screen, and
|
||||
many other UI improvements, thanks to new contributor @wsdfhjxc
|
||||
|
||||
* fixes to allow keyboard/d-pad navigation in more places, thanks to
|
||||
new contributor @doeffinger
|
||||
|
||||
### 1.4-alpha0 (2018-08-17)
|
||||
|
||||
* show "Open" button when media is installed and viewable
|
||||
|
||||
* retry index downloads from mirrors
|
||||
|
||||
* add Share button to "Installed Apps" to export CSV list
|
||||
|
||||
* add clickable list of APKs to the swap HTML index page
|
||||
|
||||
### 1.3.1 (2018-08-07)
|
||||
|
||||
* big overhaul of core nearby/swap plumbing
|
||||
|
||||
* TLSv1.3 support, when the device supports it
|
||||
|
||||
### 1.3 (2018-07-31)
|
||||
|
||||
* large overhaul to make status updates more reliable
|
||||
|
||||
* fixed many bugs around the wrong button showing
|
||||
|
||||
### 1.3-alpha5 (2018-07-21)
|
||||
|
||||
* overhaul install button logic to avoid false presses
|
||||
|
||||
* improved first time run experience
|
||||
|
||||
* export install/uninstall history
|
||||
|
||||
* more whitelabeling improvements
|
||||
|
||||
### 1.3-alpha4 (2018-07-13)
|
||||
|
||||
* fix Data/WiFi preferences to properly schedule Updats
|
||||
|
||||
* fix Install/Uninstall events for clearer feedback
|
||||
|
||||
* track pending installs properly, stop fake repeating updates
|
||||
|
||||
* add support for Repo Push Requests when using Index V1
|
||||
|
||||
* support NoSourceSince anti-feature
|
||||
|
||||
* share menu item for repos
|
||||
|
||||
* fix a few crasher bugs
|
||||
|
||||
### 1.3-alpha3 (2018-06-27)
|
||||
|
||||
* fix bug that disabled Privileged Extension
|
||||
|
||||
* prevent crash loop after rapid install/uninstall cycling
|
||||
|
||||
* add expert option to send debug version/UUID on each HTTP download
|
||||
|
||||
* allow user to disable ACRA entirely with a preference
|
||||
|
||||
* basic Install History viewer, available only when logging is enabled
|
||||
|
||||
### 1.3-alpha2 (2018-06-25)
|
||||
|
||||
* Settings improvements
|
||||
|
||||
* new Expert Setting for disabling all notifications
|
||||
|
||||
* huge improvements for custom "whitelabel" F-Droid versions
|
||||
|
||||
### 1.3-alpha1 (2018-06-15)
|
||||
|
||||
* improved Settings for controlling data usage
|
||||
|
||||
* support push install/uninstall requests in index-v1
|
||||
|
||||
### 1.3-alpha0 (2018-04-25)
|
||||
|
||||
* more battery conscious background operation on Android 5.0 and newer
|
||||
|
||||
* make Anti-Features list in App Details clickable
|
||||
|
||||
* new Settings for controlling data usage
|
||||
|
||||
* switch Settings to Material style
|
||||
|
||||
* bumped minimum supported version to Android 4.0 (14)
|
||||
|
||||
### 1.2.2 (2018-04-23)
|
||||
|
||||
* fix crasher bug on devices running on Android 4.2 or older #1424
|
||||
|
||||
### 1.2.1 (2018-04-18)
|
||||
|
||||
* improved automatic mirror selection
|
||||
|
||||
* more swap/nearby bug fixes and improvements
|
||||
|
||||
### 1.2 (2018-04-13)
|
||||
|
||||
* lots of swap/nearby bug fixes and improvements
|
||||
|
||||
* fix one cause of reoccuring update notifications (#1271)
|
||||
|
||||
* make F-Droid recognize fdroid nightly URLs from GitLab
|
||||
|
||||
### 1.2-alpha1 (2018-04-06)
|
||||
|
||||
* fix Privileged Extension install with apps with uses-permision-sdk-23
|
||||
|
||||
* automatically trim or delete cache when storage space is low
|
||||
|
||||
* improved performance on low memory devices
|
||||
|
||||
* make all downloads respect "Only on Wi-Fi" preference
|
||||
|
||||
### 1.2-alpha0 (2018-03-30)
|
||||
|
||||
* add custom mirrors to any repo by clicking links, scanning QR codes, etc.
|
||||
|
||||
* reduce memory usage when device is running low
|
||||
|
||||
### 1.1 (2018-03-21)
|
||||
|
||||
* fix some problems with items Updates reappearing
|
||||
|
||||
* fix failback install method when permissions aren't in sync #1310
|
||||
|
||||
### 1.1-alpha4 (2018-03-09)
|
||||
|
||||
* fix the most popular ACRA crash reports
|
||||
|
||||
* UI layout improvements
|
||||
|
||||
* warn users when scanning QR with camera without autofocus
|
||||
|
||||
### 1.1-alpha3 (2018-02-13)
|
||||
|
||||
* add sort button to Search view: alpha or most recent
|
||||
|
||||
* fix bugs: #1305 #1306 #1325
|
||||
|
||||
* add more detail to ACRA crash reports
|
||||
|
||||
### 1.1-alpha2 (2018-02-06)
|
||||
|
||||
* reload index after system locale change or OS upgrade
|
||||
|
||||
* add "panic responder" support
|
||||
|
||||
### 1.1-alpha1 (2018-01-26)
|
||||
|
||||
* provision new repos via a provisioning file
|
||||
|
||||
* "Android App Links" handling aka "Digital Asset Links"
|
||||
|
||||
* new privacy prefs: disable screenshots; exit on panic
|
||||
|
||||
### 1.1-alpha0 (2017-11-09)
|
||||
|
||||
* automatically choose between official repo mirrors
|
||||
|
||||
* fullscreen, swipeable app screenshot navigation
|
||||
|
||||
* new preference to prevent screenshots/recents
|
||||
|
||||
* fix crasher bug #1203
|
||||
* properly display newlines in app descriptions
|
||||
|
||||
### 1.0.1 (2017-10-23)
|
||||
|
||||
@ -462,39 +22,39 @@
|
||||
|
||||
### 1.0 (2017-10-10)
|
||||
|
||||
* Completely overhauled workflow for updating apps
|
||||
* completely overhauled workflow for updating apps
|
||||
|
||||
* Fully translatable app summaries and descriptions
|
||||
* fully translatable app summaries and descriptions
|
||||
|
||||
* "What's New" section to show changes in current release
|
||||
|
||||
* Screenshots and feature graphics
|
||||
* screenshots and feature graphics
|
||||
|
||||
* Support installing media, OTA, ZIP, etc. files
|
||||
* Support installing media, OTA, ZIP, etc files
|
||||
|
||||
* Improved protection against tracking (HTTP ETag, TLS, etc.)
|
||||
* improved protection against tracking (HTTP etag, TLS, etc.)
|
||||
|
||||
* Fully background updates with Privileged Extension
|
||||
* fully background updates with Privileged Extension
|
||||
|
||||
* Highlight donations to app developers
|
||||
* highlight donations to app developers
|
||||
|
||||
* Much faster index updates
|
||||
* much faster index updates
|
||||
|
||||
### 1.0-alpha5 (2017-10-04)
|
||||
|
||||
* Fix bug that prevented translations from showing up on Android >= 7.0 (#987)
|
||||
* fix bug that prevented translations from showing up on Android >= 7.0 (#987)
|
||||
|
||||
* Fix DB upgrade crash from 1.0-alpha3 --> 1.0-alpha4 (#1181)
|
||||
* fix db upgrade crash from 1.0-alpha3 --> 1.0-alpha4 (#1181)
|
||||
|
||||
### 1.0-alpha4 (2017-09-27)
|
||||
|
||||
* Added swipe gestures to the Updates tab
|
||||
* added swipe gestures to the Updates tab
|
||||
|
||||
* Display warnings with actions in Updates tab for KnownVulns
|
||||
* display warnings with actions in Updates tab for KnownVulns
|
||||
|
||||
* Translation updates
|
||||
* translation updates
|
||||
|
||||
* Dark UI fixes
|
||||
* dark UI fixes
|
||||
|
||||
### 1.0-alpha3 (2017-09-12)
|
||||
|
||||
@ -514,13 +74,13 @@
|
||||
|
||||
### 1.0-alpha1 (2017-07-18)
|
||||
|
||||
* Fix bug removing apps from repos (#568)
|
||||
* fix bug removing apps from repos (#568)
|
||||
|
||||
* Much faster index updates
|
||||
* much faster index updates
|
||||
|
||||
### 1.0-alpha0 (2017-07-08)
|
||||
|
||||
* Support installing media, OTA, ZIP, etc. files
|
||||
* Support installing media, OTA, ZIP, etc files
|
||||
|
||||
* Fully support APKs signed by multiple signing keys
|
||||
|
||||
@ -544,7 +104,7 @@
|
||||
|
||||
* Various stability fixes
|
||||
|
||||
* Bits of text no longer randomly switch to English
|
||||
* Bits of text no longer randomly switches to English
|
||||
|
||||
* Fix send F-Droid via Bluetooth on Android 7.x
|
||||
|
||||
@ -596,7 +156,7 @@
|
||||
|
||||
* Support for Android 2.2 is dropped, 2.3.3 or later is now required
|
||||
|
||||
* Fixed APK Cache bugs, requiring the cache time be reset to one day
|
||||
* Fixed APK Cache bugs, requiring the cache time be reset to 1 day
|
||||
|
||||
* Use Privileged Extension by default if installed
|
||||
|
||||
@ -610,7 +170,7 @@
|
||||
|
||||
* Fix crash if an app has a short description
|
||||
|
||||
* Fix background crash in the Wi-Fi state change swap service
|
||||
* Fix background crash in the wifi state change swap service
|
||||
|
||||
* Fix crash if there is a problem listing the cached files to delete
|
||||
|
||||
@ -660,7 +220,7 @@
|
||||
|
||||
* Fix crash when adding malformed URIs as repos
|
||||
|
||||
* Fix Android.mk build when the output dir. is a relative path
|
||||
* Fix Android.mk build when the output dir is a relative path
|
||||
|
||||
### 0.98 (2016-02-01)
|
||||
|
||||
@ -724,7 +284,7 @@
|
||||
|
||||
* Move the repo index update to a notification
|
||||
|
||||
* Handle APK downloads without a dialog
|
||||
* Handle apk downloads without a dialog
|
||||
|
||||
* Don't let users try to uninstall system apps that haven't been updated
|
||||
|
||||
@ -767,14 +327,14 @@
|
||||
and now easy to set up with root privileges
|
||||
|
||||
* Speed up and simplify repo update process by streaming the data out of the
|
||||
JAR file directly
|
||||
jar file directly
|
||||
|
||||
* Can now manually add swap repo via "Repositories" screen
|
||||
|
||||
* Using NFC during swap now initiates a proper swap, rather than redirecting to
|
||||
the "Repositories" screen
|
||||
|
||||
* Drop Ant support to greatly simplify the build process and its maintenance
|
||||
* Drop ant support to greatly simplify the build process and its maintenance
|
||||
|
||||
### 0.92 (2015-06-08)
|
||||
|
||||
@ -782,7 +342,7 @@
|
||||
|
||||
* Update Universal-Image-Loader to 1.9.4
|
||||
|
||||
* Make APK downloads progress be measured in kilobytes instead of bytes
|
||||
* Make Apk downloads progress be measured in kilobytes instead of bytes
|
||||
|
||||
* Add missing Sardinian language to the preferences
|
||||
|
||||
@ -795,9 +355,9 @@
|
||||
since it's not needed to use our own external app directory
|
||||
|
||||
* Fix a crash occuring if the user triggered a repo update that got rid of
|
||||
more than 450 APKs at once
|
||||
more than 450 apks at once
|
||||
|
||||
* Properly cache APK files on the SD card if configured this way
|
||||
* Properly cache apk files on the SD card if configured this way
|
||||
|
||||
* Drop support for unsigned repos in favour of signed ones and TOFU support
|
||||
|
||||
@ -811,7 +371,7 @@
|
||||
|
||||
* Don't crash if links on descriptions cannot be handled by any application
|
||||
|
||||
* Support building as part of a ROM via an Android.mk using Gradle
|
||||
* Support building as part of a ROM via an Android.mk using gradle
|
||||
|
||||
### 0.88 (2015-04-28)
|
||||
|
||||
@ -821,7 +381,7 @@
|
||||
* User interface language can now be changed from inside the F-Droid
|
||||
preferences without changing the system language (locale)
|
||||
|
||||
* Fix an issue where XML files could pile up in the data directory
|
||||
* Fix an issue where xml files could pile up in the data directory
|
||||
|
||||
* Improve app and search link handling while also adding supporting for Amazon
|
||||
and Google Play links
|
||||
@ -831,12 +391,12 @@
|
||||
|
||||
* Show a message to the user when there are no apps to display.
|
||||
|
||||
* Swapping is now two-way. Connecting to a swap on one device will
|
||||
initiate a swap on the other device
|
||||
* Swapping is now two way. Connecting to a swap on one device will
|
||||
initiate a swap on the other device.
|
||||
|
||||
* Small UI fixes to avoid overlapping text and improve app version ellipsizing
|
||||
|
||||
* Split up search terms when querying the app database—"fire fox" now
|
||||
* Split up search terms when querying the app database - "fire fox" now
|
||||
matches FireFox
|
||||
|
||||
* Ignore trailing paces in search terms introduced by some input methods
|
||||
@ -853,7 +413,7 @@
|
||||
|
||||
* Fix issue that caused the installed state label to sometimes not be updated
|
||||
|
||||
* Support for future devices with more than two CPU architectures
|
||||
* Support for future devices with more than two cpu architectures
|
||||
|
||||
* Show when packages are installed but not via F-Droid (mismatching signature)
|
||||
|
||||
@ -882,7 +442,7 @@
|
||||
|
||||
* Update Universal-Image-Loader and the Support libraries
|
||||
|
||||
* Switch the directory structure to better suit building with Gradle
|
||||
* Switch the directory structure to better suit building with gradle
|
||||
|
||||
* Translation updates
|
||||
|
||||
@ -904,14 +464,14 @@
|
||||
* HTTP Proxy support in Preferences
|
||||
|
||||
* Directly send installed apps to other devices via Bluetooth and Android Beam
|
||||
(NFC+Bluetooth), also compatible with Samsung/HTC S Beam
|
||||
(NFC+Bluetooth), also compatible with Samsung/HTC S-Beam
|
||||
|
||||
* Initial support for root and system installers, allowing the client to
|
||||
install APKs directly on its own
|
||||
install apks directly on its own
|
||||
|
||||
* Increased performance when updating from repository with many apps
|
||||
|
||||
* Switch to AppCompat from the Support library
|
||||
* Switch to Appcompat from the Support library
|
||||
|
||||
* Fix some crashes
|
||||
|
||||
@ -950,7 +510,7 @@
|
||||
* Send F-Droid via Bluetooth to any device that supports receiving APKs via
|
||||
Bluetooth (stock Android blocks APKs, most ROMs allow them)
|
||||
|
||||
* NFC support: Beam repo configs from the repo detail view (Android 4.0+),
|
||||
* NFC support: beam repo configs from the repo detail view (Android 4.0+),
|
||||
beam the F-Droid.apk from F-Droid's main screen (Android 4.1+)
|
||||
|
||||
* Support for repositories using self-signed HTTPS certificates through
|
||||
@ -964,7 +524,7 @@
|
||||
|
||||
* Major internal changes to enable F-Droid to handle repos with thousands
|
||||
of apps without slowing down too much. These internal changes will also make
|
||||
new features easier to implement
|
||||
new features easier to implement.
|
||||
|
||||
* Various fixes to layout issues introduced in 0.58
|
||||
|
||||
@ -978,7 +538,7 @@
|
||||
|
||||
* Tweaked some layouts, especially the app lists and their compact layout
|
||||
|
||||
* App lists now show more useful version information: Current version names,
|
||||
* App lists now show more useful version information: current version names,
|
||||
rather than number of versions available
|
||||
|
||||
* Reduce scroll lag in app lists by caching views in a ViewHolder
|
||||
@ -994,21 +554,21 @@
|
||||
can see what the checkbox preferences actually mean and what the edit and
|
||||
list preferences are set at
|
||||
|
||||
* Support for Dogecoin donation method added (wow)
|
||||
* Support for dogecoin donation method added (wow)
|
||||
|
||||
* Don't keep app icons older than 30 days in disc cache
|
||||
* Don't keep app icons older than 30 days on disc cache
|
||||
|
||||
* Always include incompatible APKs in memory to avoid issues with apps
|
||||
seemingly not having any APKs available
|
||||
* Always include incompatible apks in memory to avoid issues with apps
|
||||
seemingly not having any apks available
|
||||
|
||||
* Fixed a crash when trying to access a non-existing app
|
||||
|
||||
* F-Droid registers with Android to receive F-Droid URIs https://\*/fdroid/repo
|
||||
and fdroidrepos://
|
||||
|
||||
* Support including signing key fingerprint in repo URIs
|
||||
* support including signing key fingerprint in repo URIs
|
||||
|
||||
* When adding new repos that include the fingerprint, check to see whether
|
||||
* when adding new repos that include the fingerprint, check to see whether
|
||||
that repo exists in F-Droid already, and if the fingerprints match
|
||||
|
||||
* Other minor bug fixes
|
||||
@ -1019,12 +579,12 @@
|
||||
|
||||
* Fixed problems with category selection and permission lists on Android 2.X devices.
|
||||
|
||||
* Lots of translation updates, including new Norwegian translation
|
||||
* Lots of translation updates, including new Norwegian translation.
|
||||
|
||||
### 0.54 (2013-11-05)
|
||||
|
||||
* New options on the App Details screen to ignore all future updates for that
|
||||
particular app, or ignore just the current update
|
||||
particular app, or ignore just the current update.
|
||||
|
||||
* Apps with Anti-features are no longer hidden, and the corresponding
|
||||
preferences to unhide them are removed. Instead they are clearly marked on the
|
||||
@ -1033,7 +593,7 @@
|
||||
* Apps with incompatible native code architecture requirements are now correctly
|
||||
filtered.
|
||||
|
||||
* A bug that prevented update notifications from appearing has been fixed
|
||||
* A bug that prevented update notifications from appearing has been fixed.
|
||||
|
||||
* Theming support, with Light and Dark themes.
|
||||
|
||||
@ -1042,29 +602,29 @@
|
||||
installation.
|
||||
|
||||
* All app donation options have been grouped into a submenu, and Litecoin
|
||||
donation support has been added
|
||||
donation support has been added.
|
||||
|
||||
* App filter settings now take effect immediately
|
||||
* App filter settings now take effect immediately.
|
||||
|
||||
* APK native code ABIs are now shown in expert mode
|
||||
* Apk native code ABIs are now shown in expert mode.
|
||||
|
||||
* Search URIs for market://search and fdroid.search: are now handled
|
||||
* Search uris for market://search and fdroid.search: are now handled.
|
||||
|
||||
* A problem with ActionBar Up navigation on some devices has been fixed
|
||||
* A problem with ActionBar Up navigation on some devices has been fixed.
|
||||
|
||||
* Other minor bug fixes, and adjustments to spacings and layouts
|
||||
* Other minor bug fixes, and adjustments to spacings and layouts.
|
||||
|
||||
* Lots of translation updates
|
||||
* Lots of translation updates.
|
||||
|
||||
### 0.50 (2013-08-20)
|
||||
|
||||
* New basic app sharing functionality
|
||||
|
||||
* Handle f-droid.org web repo as well as market:// app URIs
|
||||
* Handle f-droid.org web repo as well as market:// app uris
|
||||
|
||||
* Search by just typing on main screen and search results screen
|
||||
|
||||
* Flattr and bitcoin donation methods added
|
||||
* Flattr and Bitcoin donation methods added
|
||||
|
||||
* Noticeable speedups when returning from installs and uninstalls
|
||||
|
||||
|
@ -26,16 +26,14 @@ track of modifications and fuzzy translations. Applying translations manually
|
||||
skips all of the fixes and checks, and overrides the fuzzy state of strings.
|
||||
|
||||
Note that you cannot change the English strings on Weblate. If you have any
|
||||
suggestions on how to improve them, open an issue or merge request like you
|
||||
would if you were making code changes. This way the changes can be reviewed
|
||||
before the source strings on Weblate are changed.
|
||||
|
||||
suggestions on how to improve them, open a merge request like you would if you
|
||||
were making code changes. This way the changes can be reviewed before the
|
||||
source strings on Weblate are changed.
|
||||
|
||||
## Code Style
|
||||
|
||||
We follow the default Android Studio code formatter (e.g. `Ctrl-Alt-L`). This
|
||||
should be more or less the same as [Android Java
|
||||
style](https://source.android.com/source/code-style.html). Some key points:
|
||||
We follow the [Android Java style](https://source.android.com/source/code-style.html).
|
||||
Some key points:
|
||||
|
||||
* Four space indentation
|
||||
* UTF-8 source files
|
||||
@ -47,35 +45,76 @@ style](https://source.android.com/source/code-style.html). Some key points:
|
||||
* Braces are always used after if, for and while
|
||||
|
||||
The current code base doesn't follow it entirely, but new code should follow
|
||||
it. We enforce some of these, but not all, via `./gradlew checkstyle`.
|
||||
it. We enforce some of these, but not all, via checkstyle.
|
||||
|
||||
## Debugging
|
||||
|
||||
To get all the logcat messages by F-Droid, you can run:
|
||||
|
||||
adb logcat | grep `adb shell ps | grep org.fdroid.fdroid | cut -c10-15`
|
||||
|
||||
## Building tips
|
||||
|
||||
* Use gradle with `--daemon` if you are going to build F-Droid multiple times.
|
||||
* If you get a message like `Could not find com.android.support:support-...`,
|
||||
make sure that you have the latest Android support maven repository.
|
||||
* When building as part of AOSP with `Android.mk`, make sure you have a
|
||||
recent version of Gradle installed as `gradlew` will not be used.
|
||||
|
||||
## Running the test suite
|
||||
|
||||
Before pushing commits to a merge request, make sure this passes:
|
||||
|
||||
./gradlew checkstyle pmd lint
|
||||
|
||||
In order to run the F-Droid test suite, you will need to have either a real device
|
||||
connected via `adb`, or an emulator running. Then, execute the following from the
|
||||
command line:
|
||||
|
||||
./gradlew check
|
||||
|
||||
Many important tests require a device or emulator, but do not work in GitLab CI.
|
||||
That mean they need to be run locally, and that is usually easiest in Android
|
||||
Studio rather than the command line.
|
||||
Note that the CI already runs the tests on an emulator, so you don't
|
||||
necessarily have to do this yourself if you open a merge request as the tests
|
||||
will get run.
|
||||
|
||||
For a quick way to run a specific JUnit/Robolectric test:
|
||||
### Running tests in Android Studio
|
||||
|
||||
./gradlew testFullDebugUnitTest --tests *LocaleSelectionTest*
|
||||
Later versions of Android Studio require tests to be run with a "Working directory"
|
||||
of `$MODULE_DIR$`.
|
||||
[To make this the default behaviour](https://code.google.com/p/android/issues/detail?id=158015#c11),
|
||||
close any projects to get the Welcome dialog. Then choose _Configure > Project Defaults >
|
||||
Run Configurations > Defaults > Android JUnit_, and change "Working directory"
|
||||
to `$MODULE_DIR$`. If you already have a project setup in Android Studio, you
|
||||
may also need to change the default in _Run > Edit Configurations... > Defaults >
|
||||
Android JUnit_.
|
||||
|
||||
For a quick way to run a specific emulator test:
|
||||
## Versioning
|
||||
|
||||
./gradlew connectedFullDebugAndroidTest \
|
||||
-Pandroid.testInstrumentationRunnerArguments.class=org.fdroid.fdroid.MainActivityExpressoTest
|
||||
Each stable version follows the `X.Y` pattern. Hotfix releases - i.e. when a
|
||||
stable has an important bug that needs immediate fixing - will follow the
|
||||
`X.Y.Z` pattern.
|
||||
|
||||
Before each stable release, a number of alpha releases will be released. They
|
||||
will follow the pattern `X.Y-alphaN`, where `N` is the current alpha number.
|
||||
These will usually include changes and new features that have not been tested
|
||||
enough for a stable release, so use at your own risk. Testers and reporters
|
||||
are very welcome.
|
||||
|
||||
## Making releases
|
||||
The version codes use a number of digits per each of these keys: `XXXYYYZNN`.
|
||||
So for example, 1.3.1 would be `1003150` and 0.95-alpha13 would be `95013`
|
||||
(leading zeros are omitted).
|
||||
|
||||
See https://gitlab.com/fdroid/wiki/-/wikis/Internal/Release-Process#fdroidclient
|
||||
Note that we use a trailing `50` for actual stable releases, so alphas are
|
||||
limited to `-alpha49`.
|
||||
|
||||
This is an example of a release process for **0.95**:
|
||||
|
||||
* We are currently at stable **0.94**
|
||||
* **0.95-alpha1** is released
|
||||
* **0.95-alpha2** is released
|
||||
* **0.95-alpha3** is released
|
||||
* `stable-v0.95` is branched and frozen
|
||||
* **0.95** is released
|
||||
* A bug is reported on the stable release and fixed
|
||||
* **0.95.1** is released with only that fix
|
||||
|
||||
As soon as a stable is tagged, master will move on to `-alpha0` on the next
|
||||
version. This is a temporary measure - until `-alpha1` is released - so that
|
||||
moving from stable to master doesn't require a downgrade. `-alpha0` versions
|
||||
will not be tagged nor released.
|
||||
|
11
FUNDING.yml
@ -1,11 +0,0 @@
|
||||
---
|
||||
liberapay: F-Droid-Data
|
||||
open_collective: F-Droid
|
||||
github:
|
||||
- f-droid
|
||||
- eighthave
|
||||
custom:
|
||||
- https://f-droid.org/donate/
|
||||
- https://www.hellotux.com/f-droid
|
||||
- https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=E2FCXCT6837GL
|
||||
- https://blockchain.info/address/15u8aAPK4jJ5N8wpWJ5gutAyyeHtKX5i18
|
14
README.md
@ -1,6 +1,6 @@
|
||||
# F-Droid Client
|
||||
|
||||
[](https://gitlab.com/fdroid/fdroidclient/-/jobs)
|
||||
[](https://gitlab.com/fdroid/fdroidclient/builds)
|
||||
[](https://hosted.weblate.org/engage/f-droid/)
|
||||
|
||||
Client for [F-Droid](https://f-droid.org), the Free Software repository system
|
||||
@ -38,7 +38,9 @@ to what Google Play does.
|
||||
|
||||
This used to be the case, but no longer is. Now the [Privileged
|
||||
Extension](https://gitlab.com/fdroid/privileged-extension) is the one that should be placed in
|
||||
the system. It can be bundled with a ROM or installed via a zip.
|
||||
the system. It can be bundled with a ROM or installed via a zip, or
|
||||
alternatively F-Droid can install it as a system app using root.
|
||||
|
||||
## License
|
||||
|
||||
This program is Free Software: You can use, study share and improve it at your
|
||||
@ -57,11 +59,3 @@ Other icons are from the
|
||||
[Material Design Icon set](https://github.com/google/material-design-icons)
|
||||
released under an
|
||||
[Attribution 4.0 International license](https://creativecommons.org/licenses/by/4.0/).
|
||||
|
||||
|
||||
## Translation
|
||||
|
||||
Everything can be translated. See
|
||||
[Translation and Localization](https://f-droid.org/docs/Translation_and_Localization)
|
||||
for more info.
|
||||
[](https://hosted.weblate.org/engage/f-droid/?utm_source=widget)
|
||||
|
23
RELEASE_CHECKLIST.md
Normal file
@ -0,0 +1,23 @@
|
||||
|
||||
# Release Checklist
|
||||
|
||||
This is the things that need to happen for all releases, alpha or stable:
|
||||
|
||||
* pull translations from Weblate: ./tools/pull-trans.sh
|
||||
|
||||
* rebase Weblate in its web interface, since we squash commits
|
||||
|
||||
* update `versionCode` in _app/build.gradle_
|
||||
|
||||
* make signed tag with version name
|
||||
|
||||
* update _metadata/org.fdroid.fdroid.txt_ in _fdroiddata_
|
||||
|
||||
## Stable releases
|
||||
|
||||
For stable releases, there are a couple more steps to do __before__
|
||||
making the release tag:
|
||||
|
||||
* update CHANGELOG.md
|
||||
|
||||
* run `./tools/trim-incomplete-translations-for-release.py`
|
328
app/build.gradle
@ -1,8 +1,9 @@
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'witness'
|
||||
apply plugin: 'checkstyle'
|
||||
apply plugin: 'pmd'
|
||||
|
||||
/* gets the version name from the latest Git tag */
|
||||
/* gets the version name from the latest Git tag, stripping the leading v off */
|
||||
def getVersionName = { ->
|
||||
def stdout = new ByteArrayOutputStream()
|
||||
exec {
|
||||
@ -12,88 +13,212 @@ def getVersionName = { ->
|
||||
return stdout.toString().trim()
|
||||
}
|
||||
|
||||
def isCi = "true" == System.getenv("CI")
|
||||
def preDexEnabled = "true" == System.getProperty("pre-dex", "true")
|
||||
repositories {
|
||||
jcenter()
|
||||
maven {
|
||||
url "https://jitpack.io"
|
||||
}
|
||||
}
|
||||
|
||||
def fullApplicationId = "org.fdroid.fdroid"
|
||||
def basicApplicationId = "org.fdroid.basic"
|
||||
// yes, this actually needs both quotes https://stackoverflow.com/a/41391841
|
||||
def privilegedExtensionApplicationId = '"org.fdroid.fdroid.privileged"'
|
||||
ext {
|
||||
supportLibVersion = '25.2.0'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile "com.android.support:support-v4:${supportLibVersion}"
|
||||
compile "com.android.support:appcompat-v7:${supportLibVersion}"
|
||||
compile "com.android.support:gridlayout-v7:${supportLibVersion}"
|
||||
compile "com.android.support:support-annotations:${supportLibVersion}"
|
||||
compile "com.android.support:recyclerview-v7:${supportLibVersion}"
|
||||
compile "com.android.support:cardview-v7:${supportLibVersion}"
|
||||
compile "com.android.support:design:${supportLibVersion}"
|
||||
compile "com.android.support:support-vector-drawable:${supportLibVersion}"
|
||||
compile 'com.android.support.constraint:constraint-layout:1.0.2'
|
||||
compile "com.android.support:palette-v7:${supportLibVersion}"
|
||||
|
||||
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
|
||||
compile 'com.google.zxing:core:3.2.1'
|
||||
compile 'eu.chainfire:libsuperuser:1.0.0.201602271131'
|
||||
compile 'cc.mvdan.accesspoint:library:0.2.0'
|
||||
compile 'info.guardianproject.netcipher:netcipher:2.0.0-alpha1'
|
||||
compile 'commons-io:commons-io:2.5'
|
||||
compile 'commons-net:commons-net:3.5'
|
||||
compile 'org.openhab.jmdns:jmdns:3.4.2'
|
||||
compile 'ch.acra:acra:4.9.1'
|
||||
compile 'io.reactivex:rxjava:1.1.0'
|
||||
compile 'io.reactivex:rxandroid:0.23.0'
|
||||
compile 'com.hannesdorfmann:adapterdelegates3:3.0.1'
|
||||
|
||||
// Migrate this to upstream https://github.com/Ashok-Varma/BottomNavigation if PR #110 gets
|
||||
// accepted to drop the minSdk to 10.
|
||||
compile('com.github.pserwylo:BottomNavigation:1.5.0') {
|
||||
// These pull our explicit dependency on 25.2.0 up to 25.3.0 which is broken
|
||||
// (https://code.google.com/p/android/issues/detail?id=251302)
|
||||
exclude module: 'appcompat-v7'
|
||||
exclude module: 'design'
|
||||
}
|
||||
|
||||
compile 'com.fasterxml.jackson.core:jackson-core:2.8.7'
|
||||
compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.7'
|
||||
compile 'com.fasterxml.jackson.core:jackson-databind:2.8.7'
|
||||
|
||||
testCompile "org.robolectric:robolectric:3.3.1"
|
||||
testCompile 'junit:junit:4.12'
|
||||
// As per https://github.com/robolectric/robolectric/issues/1932#issuecomment-219796474
|
||||
testCompile 'org.khronos:opengl-api:gl1.1-android-2.1_r1'
|
||||
testCompile "org.mockito:mockito-core:1.10.19"
|
||||
|
||||
androidTestCompile "com.android.support:support-annotations:${supportLibVersion}"
|
||||
androidTestCompile 'com.android.support.test:runner:0.5'
|
||||
androidTestCompile 'com.android.support.test:rules:0.5'
|
||||
}
|
||||
|
||||
if (!hasProperty('sourceDeps')) {
|
||||
|
||||
repositories {
|
||||
// This is here until we sort out all dependencies from mavenCentral/jcenter. Once all of
|
||||
// the dependencies below have been sorted out, this can be removed.
|
||||
flatDir {
|
||||
dirs 'libs/binaryDeps'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'com.madgag.spongycastle:pkix:1.53.0.0'
|
||||
compile 'com.madgag.spongycastle:prov:1.53.0.0'
|
||||
compile 'com.madgag.spongycastle:core:1.53.0.0'
|
||||
|
||||
// Upstream doesn't have a binary on mavenCentral/jcenter yet:
|
||||
// https://github.com/kolavar/android-support-v4-preferencefragment/issues/13
|
||||
compile(name: 'support-v4-preferencefragment-release', ext: 'aar')
|
||||
|
||||
// Fork for F-Droid, including support for https. Not merged into upstream
|
||||
// yet (seems to be a little unsupported as of late), so not using mavenCentral/jcenter.
|
||||
compile(name: 'nanohttpd-2.1.0')
|
||||
|
||||
// Upstream doesn't have a binary on mavenCentral, and it is an SVN repo on
|
||||
// Google Code. We include this code directly in this repo, and have made
|
||||
// modifications that should be pushed to anyone who wants to maintain it.
|
||||
compile(name: 'zipsigner')
|
||||
}
|
||||
|
||||
// Only do the libraries imported from maven repositories. Our own libraries
|
||||
// (like privileged-api-lib) and the prebuilt jars already checked into the
|
||||
// source code don't need to be here.
|
||||
// generate using: `gradle -q calculateChecksums | sort -V`
|
||||
dependencyVerification {
|
||||
verify = [
|
||||
'cc.mvdan.accesspoint:library:0837b38adb48b66bb1385adb6ade8ecce7002ad815c55abf13517c82193458ea',
|
||||
'ch.acra:acra:d2762968c448757a7d6acc9f141881d9632f664988e9723ece33b5f7c79f3bc9',
|
||||
'commons-io:commons-io:a10418348d234968600ccb1d988efcbbd08716e1d96936ccc1880e7d22513474',
|
||||
'commons-net:commons-net:c25b0da668b3c5649f002d504def22d1b4cb30d206f05428d2fe168fa1a901c2',
|
||||
'com.android.support.constraint:constraint-layout-solver:8c62525a9bc5cff5633a96cb9b32fffeccaf41b8841aa87fc22607070dea9b8d',
|
||||
'com.android.support.constraint:constraint-layout:b0c688cc2b7172608f8153a689d746da40f71e52d7e2fe2bfd9df2f92db77085',
|
||||
'com.android.support:animated-vector-drawable:d2d59a11809abe3e64535346f05c22437b458de115f06ea35021fd0714960213',
|
||||
'com.android.support:appcompat-v7:120f3ce6cac682d69e53d80ccfa9cee076f0f11ccbe56d4ccd72099a745e81f9',
|
||||
'com.android.support:cardview-v7:c8610b0c334e4438d7e1ac58fcf2ac891fb26bac662c8351cd6b345c8d7b7076',
|
||||
'com.android.support:design:bf92337c5d0931df50a0dcec81682186dc1fbcf14c2fa1c6d51976963379b64d',
|
||||
'com.android.support:gridlayout-v7:257ac1280f2b3cc3c0afca1cd4d4d2e0b923b92a76b61a9c09fc57e892da7360',
|
||||
'com.android.support:palette-v7:e0050715e0d06fabcc8721b0c2893545fb00be9d761a6ef59ae69101d2368551',
|
||||
'com.android.support:recyclerview-v7:d6ba2c3a6196cc464eb4d69756229523a46eef7804991e5a8cf2d6306dbff10c',
|
||||
'com.android.support:support-annotations:47a2a30eab487a490a8a8f16678007c3d2b6dcae1e09b0485a12bbf921200ec3',
|
||||
'com.android.support:support-compat:5a7b6e18903458e3a561df24033476518f998cd7ae1ed747c2874e0685b999c7',
|
||||
'com.android.support:support-core-ui:cf3c75fd9a1b1dcbb6042d610515cd79cd0d65d3efd272d2250727187e8ca2ed',
|
||||
'com.android.support:support-core-utils:e0561cc9d00ae125d9e1ad8985d4639e68ce8399ae973e91674e97faaf658243',
|
||||
'com.android.support:support-fragment:f12633dd4d418a4edeb5ecf3bf4393edd0770b1eaa5d1ee3078c5e7c174868fd',
|
||||
'com.android.support:support-media-compat:e9f820d08e6a5735cfdb2a7d81d3c86b4a31897ac1edaeb55c7de06bcb370343',
|
||||
'com.android.support:support-v4:cd030f875dc7ee73b58e17598f368a2e12824fb3ceb4ed515ed815a47160228c',
|
||||
'com.android.support:support-vector-drawable:d79752fd68db5a8f5c18125517dafb9e4d7b593c755d188986010e15edd62454',
|
||||
'com.android.support:transition:5a4adefb1b410b23ad62b4477bc612edc47d3dfc8efed488deb8223b70b510d7',
|
||||
'com.fasterxml.jackson.core:jackson-annotations:6b7802f6c22c09c4a92a2ebeb76e755c3c0a58dfbf419835fae470d89e469b86',
|
||||
'com.fasterxml.jackson.core:jackson-core:256ff34118ab292d1b4f3ee4d2c3e5e5f0f609d8e07c57e8ad1f51c46d4fbb46',
|
||||
'com.fasterxml.jackson.core:jackson-databind:4f74337b6d18664be0f5b15c6664b17aa3972c9c175092328b139b894ff66f19',
|
||||
'com.github.pserwylo:BottomNavigation:83d7941a7a8d21ba1a8a708cd683b1bb07c6cf898044dc92eadf18a7a7d54f90',
|
||||
'com.google.zxing:core:b4d82452e7a6bf6ec2698904b332431717ed8f9a850224f295aec89de80f2259',
|
||||
'com.hannesdorfmann:adapterdelegates3:1b20d099d6e7afe57aceca13b713b386959d94a247c3c06a7aeb65b866ece02f',
|
||||
'com.madgag.spongycastle:core:9b6b7ac856b91bcda2ede694eccd26cefb0bf0b09b89f13cda05b5da5ff68c6b',
|
||||
'com.madgag.spongycastle:pkix:6aba9b2210907a3d46dd3dcac782bb3424185290468d102d5207ebdc9796a905',
|
||||
'com.madgag.spongycastle:prov:029f26cd6b67c06ffa05702d426d472c141789001bcb15b7262ed86c868e5643',
|
||||
'com.nostra13.universalimageloader:universal-image-loader:dbd5197ffec3a8317533190870a7c00ff3750dd6a31241448c6a5522d51b65b4',
|
||||
'eu.chainfire:libsuperuser:018344ff19ee94d252c14b4a503ee8b519184db473a5af83513f5837c413b128',
|
||||
'info.guardianproject.netcipher:netcipher:eeeb5d0d95ccfe176b4296cbd71a9a24c6efb0bab5c4025a8c6bc36abdddfc75',
|
||||
'io.reactivex:rxandroid:35c1a90f8c1f499db3c1f3d608e1f191ac8afddb10c02dd91ef04c03a0a4bcda',
|
||||
'io.reactivex:rxjava:2c162afd78eba217cdfee78b60e85d3bfb667db61e12bc95e3cf2ddc5beeadf6',
|
||||
'org.openhab.jmdns:jmdns:7a4b34b5606bbd2aff7fdfe629edcb0416fccd367fb59a099f210b9aba4f0bce',
|
||||
]
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
logger.info "Setting up *source* dependencies for F-Droid (because you passed in the -PsourceDeps argument to gradle while building)."
|
||||
|
||||
dependencies {
|
||||
compile(project(':extern:support-v4-preferencefragment')) {
|
||||
exclude module: 'support-v4'
|
||||
}
|
||||
compile project(':extern:nanohttpd:core')
|
||||
compile project(':extern:zipsigner')
|
||||
}
|
||||
|
||||
task binaryDeps(type: Copy, dependsOn: ':app:prepareReleaseDependencies') {
|
||||
|
||||
enabled = project.hasProperty('sourceDeps')
|
||||
description = "Copies .jar and .aar files from subproject dependencies in extern/ to app/libs. Requires the sourceDeps property to be set (\"gradle -PsourceDeps binaryDeps\")"
|
||||
|
||||
from('../extern/') {
|
||||
include 'support-v4-preferencefragment/build/outputs/aar/support-v4-preferencefragment-release.aar'
|
||||
include 'nanohttpd/core/build/libs/nanohttpd-2.1.0.jar'
|
||||
include 'zipsigner/build/libs/zipsigner.jar'
|
||||
}
|
||||
|
||||
into 'libs/binaryDeps'
|
||||
includeEmptyDirs false
|
||||
|
||||
eachFile { FileCopyDetails details ->
|
||||
// Don't copy to a sub folder such as libs/binaryDeps/Project/build/outputs/aar/project.aar, but
|
||||
// rather libs/binaryDeps/project.aar.
|
||||
details.path = details.name
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdkVersion 30
|
||||
|
||||
defaultConfig {
|
||||
versionCode 1013001
|
||||
versionName getVersionName()
|
||||
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
minSdkVersion 24
|
||||
//noinspection ExpiredTargetSdkVersion
|
||||
targetSdkVersion 28
|
||||
/*
|
||||
The Android Testing Support Library collects analytics to continuously improve the testing
|
||||
experience. More specifically, it uploads a hash of the package name of the application
|
||||
under test for each invocation. If you do not wish to upload this data, you can opt-out by
|
||||
passing the following argument to the test runner: disableAnalytics "true".
|
||||
*/
|
||||
testInstrumentationRunnerArguments disableAnalytics: 'true'
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
}
|
||||
compileSdkVersion 24
|
||||
buildToolsVersion '25.0.2'
|
||||
useLibrary 'org.apache.http.legacy'
|
||||
|
||||
buildTypes {
|
||||
// use proguard on debug too since we have unknowingly broken
|
||||
// release builds before.
|
||||
all {
|
||||
minifyEnabled true
|
||||
useProguard true
|
||||
shrinkResources true
|
||||
buildConfigField "String", "PRIVILEGED_EXTENSION_PACKAGE_NAME", privilegedExtensionApplicationId
|
||||
buildConfigField "String", "ACRA_REPORT_EMAIL", '"reports@f-droid.org"' // String needs both quotes
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
testProguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'src/androidTest/proguard-rules.pro'
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix ".debug"
|
||||
resValue "string", "applicationId", fullApplicationId + applicationIdSuffix
|
||||
versionNameSuffix "-debug"
|
||||
println 'buildTypes.debug defaultConfig.versionCode ' + defaultConfig.versionCode
|
||||
}
|
||||
}
|
||||
|
||||
flavorDimensions "base"
|
||||
productFlavors {
|
||||
full {
|
||||
dimension "base"
|
||||
applicationId fullApplicationId
|
||||
resValue "string", "applicationId", fullApplicationId
|
||||
}
|
||||
basic {
|
||||
dimension "base"
|
||||
applicationId basicApplicationId
|
||||
resValue "string", "applicationId", basicApplicationId
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
compileOptions.encoding = "UTF-8"
|
||||
sourceCompatibility JavaVersion.VERSION_1_8
|
||||
targetCompatibility JavaVersion.VERSION_1_8
|
||||
|
||||
// Use Java 1.7, requires minSdk 8
|
||||
sourceCompatibility JavaVersion.VERSION_1_7
|
||||
targetCompatibility JavaVersion.VERSION_1_7
|
||||
}
|
||||
|
||||
aaptOptions {
|
||||
cruncherEnabled = false
|
||||
}
|
||||
|
||||
dexOptions {
|
||||
// Improve build server performance by allowing disabling of pre-dexing
|
||||
// see http://tools.android.com/tech-docs/new-build-system/tips#TOC-Improving-Build-Server-performance
|
||||
// Skip pre-dexing when running on CI or when disabled via -Dpre-dex=false.
|
||||
preDexLibraries = preDexEnabled && !isCi
|
||||
defaultConfig {
|
||||
versionCode 1000013
|
||||
versionName getVersionName()
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests {
|
||||
includeAndroidResources = true
|
||||
// prevent tests from dying on android.util.Log calls
|
||||
returnDefaultValues = true
|
||||
all {
|
||||
@ -102,10 +227,6 @@ android {
|
||||
events "skipped", "failed", "standardOut", "standardError"
|
||||
showStandardStreams = true
|
||||
}
|
||||
systemProperty 'robolectric.dependency.repo.url', 'https://repo1.maven.org/maven2'
|
||||
|
||||
// hack to avoid memory leak crashes
|
||||
forkEvery = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -141,59 +262,6 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.appcompat:appcompat:1.3.0'
|
||||
implementation 'androidx.preference:preference:1.1.1'
|
||||
implementation 'androidx.gridlayout:gridlayout:1.0.0'
|
||||
implementation 'androidx.recyclerview:recyclerview:1.1.0'
|
||||
implementation 'androidx.cardview:cardview:1.0.0'
|
||||
implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
|
||||
implementation 'androidx.palette:palette:1.0.0'
|
||||
implementation 'androidx.work:work-runtime:2.4.0'
|
||||
|
||||
implementation 'com.google.android.material:material:1.3.0'
|
||||
|
||||
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
|
||||
implementation 'com.google.zxing:core:3.3.3'
|
||||
implementation 'info.guardianproject.netcipher:netcipher:2.2.0-alpha'
|
||||
implementation 'info.guardianproject.panic:panic:1.0'
|
||||
implementation 'commons-io:commons-io:2.6'
|
||||
implementation 'commons-net:commons-net:3.6'
|
||||
implementation 'ch.acra:acra:4.9.1'
|
||||
implementation 'com.hannesdorfmann:adapterdelegates3:3.0.1'
|
||||
|
||||
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
|
||||
implementation 'io.reactivex.rxjava3:rxjava:3.0.9'
|
||||
|
||||
implementation 'com.fasterxml.jackson.core:jackson-core:2.11.1'
|
||||
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.11.1'
|
||||
implementation 'com.fasterxml.jackson.core:jackson-databind:2.11.1'
|
||||
|
||||
implementation 'org.bouncycastle:bcprov-jdk15on:1.65'
|
||||
fullImplementation 'org.bouncycastle:bcpkix-jdk15on:1.65'
|
||||
fullImplementation 'cc.mvdan.accesspoint:library:0.2.0'
|
||||
fullImplementation 'org.jmdns:jmdns:3.5.5'
|
||||
fullImplementation 'org.nanohttpd:nanohttpd:2.3.1'
|
||||
|
||||
testImplementation 'androidx.test:core:1.3.0'
|
||||
testImplementation 'junit:junit:4.13.1'
|
||||
testImplementation 'org.robolectric:robolectric:4.3'
|
||||
testImplementation 'org.mockito:mockito-core:3.3.3'
|
||||
testImplementation 'org.hamcrest:hamcrest:2.2'
|
||||
testImplementation 'org.bouncycastle:bcprov-jdk15on:1.65'
|
||||
|
||||
androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
|
||||
androidTestImplementation 'androidx.test:core:1.3.0'
|
||||
androidTestImplementation 'androidx.test:runner:1.3.0'
|
||||
androidTestImplementation 'androidx.test:rules:1.3.0'
|
||||
androidTestImplementation 'androidx.test:monitor:1.3.0'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
|
||||
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
|
||||
androidTestImplementation 'androidx.work:work-testing:2.4.0'
|
||||
}
|
||||
|
||||
checkstyle {
|
||||
toolVersion = '7.2'
|
||||
}
|
||||
@ -207,7 +275,7 @@ task checkstyle(type: Checkstyle) {
|
||||
}
|
||||
|
||||
pmd {
|
||||
toolVersion = '6.20.0'
|
||||
toolVersion = '5.5.1'
|
||||
consoleOutput = true
|
||||
}
|
||||
|
||||
@ -228,3 +296,35 @@ task pmdTest(type: Pmd) {
|
||||
}
|
||||
|
||||
task pmd(dependsOn: [pmdMain, pmdTest]) {}
|
||||
|
||||
// This person took the example code below from another blogpost online, however
|
||||
// I lost the reference to it:
|
||||
// http://stackoverflow.com/questions/23297562/gradle-javadoc-and-android-documentation
|
||||
android.applicationVariants.all { variant ->
|
||||
|
||||
task("generate${variant.name}Javadoc", type: Javadoc) {
|
||||
title = "$name $version API"
|
||||
description "Generates Javadoc for F-Droid."
|
||||
source = variant.javaCompile.source
|
||||
|
||||
def sdkDir
|
||||
Properties properties = new Properties()
|
||||
File localProps = project.rootProject.file('local.properties')
|
||||
if (localProps.exists()) {
|
||||
properties.load(localProps.newDataInputStream())
|
||||
sdkDir = properties.getProperty('sdk.dir')
|
||||
} else {
|
||||
sdkDir = System.getenv('ANDROID_HOME')
|
||||
}
|
||||
if (!sdkDir) {
|
||||
throw new ProjectConfigurationException("Cannot find android sdk. Make sure sdk.dir is defined in local.properties or the environment variable ANDROID_HOME is set.", null)
|
||||
}
|
||||
|
||||
ext.androidJar = "${sdkDir}/platforms/${android.compileSdkVersion}/android.jar"
|
||||
classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar)
|
||||
options.links("http://docs.oracle.com/javase/7/docs/api/");
|
||||
options.links("http://d.android.com/reference/");
|
||||
exclude '**/BuildConfig.java'
|
||||
exclude '**/R.java'
|
||||
}
|
||||
}
|
||||
|
BIN
app/libs/binaryDeps/nanohttpd-2.1.0.jar
Normal file
BIN
app/libs/binaryDeps/support-v4-preferencefragment-release.aar
Normal file
BIN
app/libs/binaryDeps/zipsigner.jar
Normal file
28
app/lint.xml
@ -6,42 +6,19 @@
|
||||
<!-- to make CI fail on errors until this is fixed
|
||||
https://github.com/rtyley/spongycastle/issues/7 -->
|
||||
<issue id="InvalidPackage" severity="warning"/>
|
||||
|
||||
<issue id="ImpliedQuantity" severity="error"/>
|
||||
<issue id="DefaultLocale" severity="error"/>
|
||||
<issue id="SimpleDateFormat" severity="error"/>
|
||||
<issue id="NewApi" severity="error"/>
|
||||
<issue id="InlinedApi" severity="error"/>
|
||||
|
||||
<!-- These are important to us, so promote from warning to error -->
|
||||
<issue id="UnusedResources" severity="error">
|
||||
<ignore path="src/main/res/drawable/category_**.png" />
|
||||
<ignore path="src/main/res/values/dimens.xml"/>
|
||||
<ignore path="src/main/res/values/styles.xml"/>
|
||||
<ignore path="src/full/res/values/styles.xml"/>
|
||||
<!-- keep a single strings.xml for all build flavors -->
|
||||
<ignore path="src/main/res/values**/strings.xml"/>
|
||||
</issue>
|
||||
<issue id="AppCompatMethod" severity="error"/>
|
||||
<issue id="NestedScrolling" severity="error"/>
|
||||
<issue id="Typos" severity="error"/>
|
||||
<issue id="StringFormatCount" severity="error"/>
|
||||
<issue id="UnsafeProtectedBroadcastReceiver" severity="error"/>
|
||||
<issue id="GetInstance" severity="error"/>
|
||||
<issue id="PackageManagerGetSignatures" severity="error"/>
|
||||
<issue id="HardwareIds" severity="error"/>
|
||||
<issue id="TrustAllX509TrustManager" severity="error">
|
||||
<!-- these come from included libraries -->
|
||||
<ignore path="org/apache/commons/net/ftp/FTPSTrustManager.class"/>
|
||||
<ignore path="org/bouncycastle/est/jcajce/JcaJceUtils$1.class"/>
|
||||
<ignore path="org/bouncycastle/est/jcajce/JcaJceUtils$2.class"/>
|
||||
<ignore path="org/apache/commons/net/util/TrustManagerUtils$TrustManager.class"/>
|
||||
</issue>
|
||||
|
||||
<issue id="PluralsCandidate" severity="error"/>
|
||||
<issue id="HardcodedText" severity="error"/>
|
||||
<issue id="RtlCompat" severity="error"/>
|
||||
<issue id="RtlEnabled" severity="error"/>
|
||||
|
||||
<!-- both the correct and deprecated locales need to be present for
|
||||
them to be recognized on all devices -->
|
||||
@ -54,11 +31,6 @@
|
||||
<ignore path="src/main/java/org/fdroid/fdroid/installer/ApkFileProvider.java"/>
|
||||
</issue>
|
||||
|
||||
<issue id="ProtectedPermissions" severity="error">
|
||||
<ignore path="src/debug/AndroidManifest.xml"/>
|
||||
<ignore path="src/full/AndroidManifest.xml"/>
|
||||
</issue>
|
||||
|
||||
<!-- these should be fixed, but it'll be a chunk of work -->
|
||||
<issue id="SetTextI18n" severity="error">
|
||||
<ignore path="src/main/java/org/fdroid/fdroid/views/AppDetailsRecyclerViewAdapter.java"/>
|
||||
|
33
app/proguard-rules.pro
vendored
@ -4,16 +4,12 @@
|
||||
-keep class org.fdroid.fdroid.** {*;}
|
||||
-dontskipnonpubliclibraryclassmembers
|
||||
-dontwarn android.test.**
|
||||
-dontwarn com.android.support.test.**
|
||||
|
||||
-dontwarn javax.naming.**
|
||||
-dontwarn org.slf4j.**
|
||||
-dontnote org.apache.http.**
|
||||
-dontnote android.net.http.**
|
||||
-dontnote android.support.**
|
||||
-dontnote **ILicensingService
|
||||
|
||||
# Needed for espresso https://stackoverflow.com/a/21706087
|
||||
-dontwarn org.xmlpull.v1.**
|
||||
|
||||
# StrongHttpsClient and its support classes are totally unused, so the
|
||||
# ch.boye.httpclientandroidlib.** classes are also unneeded
|
||||
-dontwarn info.guardianproject.netcipher.client.**
|
||||
@ -23,7 +19,7 @@
|
||||
# removed, proguard will strip classes which are required, which may result in
|
||||
# crashes.
|
||||
-keep class kellinwood.security.zipsigner.** {*;}
|
||||
-keep class org.bouncycastle.** {*;}
|
||||
-keep class org.spongycastle.** {*;}
|
||||
|
||||
# This keeps class members used for SystemInstaller IPC.
|
||||
# Reference: https://gitlab.com/fdroid/fdroidclient/issues/79
|
||||
@ -31,6 +27,24 @@
|
||||
public *;
|
||||
}
|
||||
|
||||
# Samsung Android 4.2 bug
|
||||
# https://code.google.com/p/android/issues/detail?id=78377
|
||||
-keepnames class !android.support.v7.internal.view.menu.**, ** {*;}
|
||||
|
||||
-keep public class android.support.v7.widget.** {*;}
|
||||
-keep public class android.support.v7.internal.widget.** {*;}
|
||||
|
||||
-keep public class * extends android.support.v4.view.ActionProvider {
|
||||
public <init>(android.content.Context);
|
||||
}
|
||||
|
||||
# The rxjava library depends on sun.misc.Unsafe, which is unavailable on Android
|
||||
# The rxjava team is aware of this, and mention in the docs that they only use
|
||||
# the unsafe functionality if the platform supports it.
|
||||
# - https://github.com/ReactiveX/RxJava/issues/1415#issuecomment-48390883
|
||||
# - https://github.com/ReactiveX/RxJava/blob/1.x/src/main/java/rx/internal/util/unsafe/UnsafeAccess.java#L23
|
||||
-dontwarn rx.internal.util.**
|
||||
|
||||
-keepattributes *Annotation*,EnclosingMethod,Signature
|
||||
-keepnames class com.fasterxml.jackson.** { *; }
|
||||
-dontwarn com.fasterxml.jackson.databind.ext.**
|
||||
@ -40,8 +54,3 @@ public static final org.codehaus.jackson.annotate.JsonAutoDetect$Visibility *; }
|
||||
-keep public class your.class.** {
|
||||
*;
|
||||
}
|
||||
|
||||
# This is necessary so that RemoteWorkManager can be initialized (also marked with @Keep)
|
||||
-keep class androidx.work.multiprocess.RemoteWorkManagerClient {
|
||||
public <init>(...);
|
||||
}
|
@ -1,24 +1,23 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
package="org.fdroid.fdroid.tests"
|
||||
android:versionCode="1"
|
||||
android:versionName="1.0">
|
||||
|
||||
<uses-sdk tools:overrideLibrary="android_libs.ub_uiautomator" />
|
||||
|
||||
<!-- We add an application tag here just so that we can indicate that
|
||||
this package needs to link against the android.test library,
|
||||
which is needed when building test cases. -->
|
||||
<application>
|
||||
<uses-library
|
||||
android:name="android.test.runner"
|
||||
android:required="false" />
|
||||
<uses-library android:name="android.test.runner"/>
|
||||
</application>
|
||||
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<!--
|
||||
This declares that this application uses the instrumentation test runner targeting
|
||||
the package of org.fdroid.fdroid. To run the tests use the command:
|
||||
"adb shell am instrument -w org.fdroid.fdroid.tests/android.test.InstrumentationTestRunner"
|
||||
-->
|
||||
<instrumentation android:name="com.zutubi.android.junitreport.JUnitReportTestRunner"
|
||||
android:targetPackage="org.fdroid.fdroid"
|
||||
android:label="Tests for org.fdroid.fdroid" />
|
||||
</manifest>
|
||||
|
@ -68,7 +68,7 @@
|
||||
</permissions>
|
||||
<uses-permission name="android.permission.GET_ACCOUNTS" maxSdkVersion="22" />
|
||||
<uses-permission name="android.permission.READ_EXTERNAL_STORAGE" maxSdkVersion="18" />
|
||||
<uses-permission name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission name="android.permission.WRITE_EXTERNAL_STORAGE" maxSdkVersion="18" />
|
||||
<uses-permission name="android.permission.AUTHENTICATE_ACCOUNTS" maxSdkVersion="22" />
|
||||
<uses-permission name="android.permission.MANAGE_ACCOUNTS" maxSdkVersion="22" />
|
||||
</package>
|
||||
@ -85,7 +85,7 @@
|
||||
<targetSdkVersion>23</targetSdkVersion>
|
||||
<added>2016-06-26</added>
|
||||
<permissions>
|
||||
org.dmfs.permission.READ_TASKS,WRITE_CONTACTS,GET_ACCOUNTS,AUTHENTICATE_ACCOUNTS,WRITE_EXTERNAL_STORAGE,READ_CALENDAR,ACCESS_WIFI_STATE,org.dmfs.permission.WRITE_TASKS,ACCESS_NETWORK_STATE,WRITE_CALENDAR,READ_CONTACTS,READ_SYNC_SETTINGS,INTERNET,MANAGE_ACCOUNTS,WRITE_SYNC_SETTINGS
|
||||
org.dmfs.permission.READ_TASKS,READ_EXTERNAL_STORAGE,WRITE_CONTACTS,GET_ACCOUNTS,AUTHENTICATE_ACCOUNTS,WRITE_EXTERNAL_STORAGE,READ_CALENDAR,ACCESS_WIFI_STATE,org.dmfs.permission.WRITE_TASKS,ACCESS_NETWORK_STATE,WRITE_CALENDAR,READ_CONTACTS,READ_SYNC_SETTINGS,INTERNET,MANAGE_ACCOUNTS,WRITE_SYNC_SETTINGS
|
||||
</permissions>
|
||||
</package>
|
||||
<package>
|
||||
|
@ -1,8 +1,8 @@
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import android.content.Context;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
@ -16,9 +16,6 @@ public class AssetUtils {
|
||||
|
||||
private static final String TAG = "Utils";
|
||||
|
||||
/**
|
||||
* This requires {@link Context} from {@link android.app.Instrumentation#getContext()}
|
||||
*/
|
||||
@Nullable
|
||||
public static File copyAssetToDir(Context context, String assetName, File directory) {
|
||||
File tempFile = null;
|
||||
@ -31,7 +28,6 @@ public class AssetUtils {
|
||||
output = new FileOutputStream(tempFile);
|
||||
Utils.copy(input, output);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Check the context is from Instrumentation.getContext()");
|
||||
fail(e.getMessage());
|
||||
} finally {
|
||||
Utils.closeQuietly(output);
|
||||
|
@ -0,0 +1,65 @@
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import android.app.Instrumentation;
|
||||
import android.support.test.InstrumentationRegistry;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.fdroid.fdroid.compat.FileCompatTest;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class CleanCacheServiceTest {
|
||||
|
||||
public static final String TAG = "CleanCacheServiceTest";
|
||||
|
||||
@Test
|
||||
public void testClearOldFiles() throws IOException, InterruptedException {
|
||||
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
||||
File tempDir = FileCompatTest.getWriteableDir(instrumentation);
|
||||
assertTrue(tempDir.isDirectory());
|
||||
assertTrue(tempDir.canWrite());
|
||||
|
||||
File dir = new File(tempDir, "F-Droid-test.clearOldFiles");
|
||||
FileUtils.deleteQuietly(dir);
|
||||
assertTrue(dir.mkdirs());
|
||||
assertTrue(dir.isDirectory());
|
||||
|
||||
File first = new File(dir, "first");
|
||||
first.deleteOnExit();
|
||||
|
||||
File second = new File(dir, "second");
|
||||
second.deleteOnExit();
|
||||
|
||||
assertFalse(first.exists());
|
||||
assertFalse(second.exists());
|
||||
|
||||
assertTrue(first.createNewFile());
|
||||
assertTrue(first.exists());
|
||||
|
||||
Thread.sleep(7000);
|
||||
assertTrue(second.createNewFile());
|
||||
assertTrue(second.exists());
|
||||
|
||||
CleanCacheService.clearOldFiles(dir, 3000); // check all in dir
|
||||
assertFalse(first.exists());
|
||||
assertTrue(second.exists());
|
||||
|
||||
Thread.sleep(7000);
|
||||
CleanCacheService.clearOldFiles(second, 3000); // check just second file
|
||||
assertFalse(first.exists());
|
||||
assertFalse(second.exists());
|
||||
|
||||
// make sure it doesn't freak out on a non-existant file
|
||||
File nonexistant = new File(tempDir, "nonexistant");
|
||||
CleanCacheService.clearOldFiles(nonexistant, 1);
|
||||
CleanCacheService.clearOldFiles(null, 1);
|
||||
}
|
||||
}
|
@ -5,8 +5,8 @@ import android.content.Context;
|
||||
import android.content.res.AssetManager;
|
||||
import android.content.res.Configuration;
|
||||
import android.content.res.Resources;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import android.support.test.InstrumentationRegistry;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.text.TextUtils;
|
||||
import android.util.DisplayMetrics;
|
||||
import android.util.Log;
|
||||
@ -102,7 +102,7 @@ public class LocalizationTest {
|
||||
String formats = null;
|
||||
try {
|
||||
int resId = field.getInt(int.class);
|
||||
for (int quantity = 0; quantity < 567; quantity++) {
|
||||
for (int quantity = 0; quantity < 22; quantity++) {
|
||||
resources.getQuantityString(resId, quantity);
|
||||
}
|
||||
|
||||
@ -179,15 +179,9 @@ public class LocalizationTest {
|
||||
case "dd":
|
||||
resources.getString(resId, 1, 2);
|
||||
break;
|
||||
case "ds":
|
||||
resources.getString(resId, 1, "TWO");
|
||||
break;
|
||||
case "dds":
|
||||
resources.getString(resId, 1, 2, "THREE");
|
||||
break;
|
||||
case "sds":
|
||||
resources.getString(resId, "ONE", 2, "THREE");
|
||||
break;
|
||||
case "s":
|
||||
resources.getString(resId, "ONE");
|
||||
break;
|
||||
|
@ -1,303 +0,0 @@
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.ActivityManager;
|
||||
import android.app.Instrumentation;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.test.core.app.ApplicationProvider;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.espresso.IdlingPolicies;
|
||||
import androidx.test.espresso.ViewInteraction;
|
||||
import androidx.test.rule.ActivityTestRule;
|
||||
import androidx.test.rule.GrantPermissionRule;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.uiautomator.UiDevice;
|
||||
import androidx.test.uiautomator.UiObject;
|
||||
import androidx.test.uiautomator.UiObjectNotFoundException;
|
||||
import androidx.test.uiautomator.UiSelector;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import org.fdroid.fdroid.views.StatusBanner;
|
||||
import org.fdroid.fdroid.views.main.MainActivity;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static androidx.test.espresso.Espresso.onView;
|
||||
import static androidx.test.espresso.action.ViewActions.click;
|
||||
import static androidx.test.espresso.action.ViewActions.swipeDown;
|
||||
import static androidx.test.espresso.action.ViewActions.swipeLeft;
|
||||
import static androidx.test.espresso.action.ViewActions.swipeRight;
|
||||
import static androidx.test.espresso.action.ViewActions.swipeUp;
|
||||
import static androidx.test.espresso.action.ViewActions.typeText;
|
||||
import static androidx.test.espresso.assertion.ViewAssertions.doesNotExist;
|
||||
import static androidx.test.espresso.assertion.ViewAssertions.matches;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static androidx.test.espresso.matcher.ViewMatchers.withText;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
@LargeTest
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class MainActivityEspressoTest {
|
||||
public static final String TAG = "MainActivityEspressoTest";
|
||||
|
||||
/**
|
||||
* Emulators older than {@code android-25} seem to fail at running Espresso tests.
|
||||
* <p>
|
||||
* ARM emulators are too slow to run these tests in a useful way. The sad
|
||||
* thing is that it would probably work if Android didn't put up the ANR
|
||||
* "Process system isn't responding" on boot each time. There seems to be no
|
||||
* way to increase the ANR timeout.
|
||||
*/
|
||||
private static boolean canRunEspresso() {
|
||||
if (Build.VERSION.SDK_INT < 25
|
||||
|| (Build.SUPPORTED_ABIS[0].startsWith("arm") && isEmulator())) {
|
||||
Log.e(TAG, "SKIPPING TEST: ARM emulators are too slow to run these tests in a useful way");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void classSetUp() {
|
||||
IdlingPolicies.setIdlingResourceTimeout(10, TimeUnit.MINUTES);
|
||||
IdlingPolicies.setMasterPolicyTimeout(10, TimeUnit.MINUTES);
|
||||
if (!canRunEspresso()) {
|
||||
return;
|
||||
}
|
||||
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
||||
try {
|
||||
UiDevice.getInstance(instrumentation)
|
||||
.executeShellCommand("pm grant "
|
||||
+ instrumentation.getTargetContext().getPackageName()
|
||||
+ " android.permission.SET_ANIMATION_SCALE");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
SystemAnimations.disableAll(ApplicationProvider.getApplicationContext());
|
||||
|
||||
// dismiss the ANR or any other system dialogs that might be there
|
||||
UiObject button = new UiObject(new UiSelector().text("Wait").enabled(true));
|
||||
try {
|
||||
button.click();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
Log.d(TAG, e.getLocalizedMessage());
|
||||
}
|
||||
new UiWatchers().registerAnrAndCrashWatchers();
|
||||
|
||||
Context context = instrumentation.getTargetContext();
|
||||
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
|
||||
ActivityManager activityManager = ContextCompat.getSystemService(context, ActivityManager.class);
|
||||
activityManager.getMemoryInfo(mi);
|
||||
long percentAvail = mi.availMem / mi.totalMem;
|
||||
Log.i(TAG, "RAM: " + mi.availMem + " / " + mi.totalMem + " = " + percentAvail);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void classTearDown() {
|
||||
SystemAnimations.enableAll(ApplicationProvider.getApplicationContext());
|
||||
}
|
||||
|
||||
public static boolean isEmulator() {
|
||||
return Build.FINGERPRINT.startsWith("generic")
|
||||
|| Build.FINGERPRINT.startsWith("unknown")
|
||||
|| Build.MODEL.contains("google_sdk")
|
||||
|| Build.MODEL.contains("Emulator")
|
||||
|| Build.MODEL.contains("Android SDK built for x86")
|
||||
|| Build.MANUFACTURER.contains("Genymotion")
|
||||
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|
||||
|| "google_sdk".equals(Build.PRODUCT);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
assumeTrue(canRunEspresso());
|
||||
}
|
||||
|
||||
/**
|
||||
* Placate {@link android.os.StrictMode}
|
||||
*
|
||||
* @see <a href="https://github.com/aosp-mirror/platform_frameworks_base/commit/6f3a38f3afd79ed6dddcef5c83cb442d6749e2ff"> Run finalizers before counting for StrictMode</a>
|
||||
*/
|
||||
@After
|
||||
public void tearDown() {
|
||||
System.gc();
|
||||
System.runFinalization();
|
||||
System.gc();
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ActivityTestRule<MainActivity> activityTestRule =
|
||||
new ActivityTestRule<>(MainActivity.class);
|
||||
|
||||
@Rule
|
||||
public GrantPermissionRule accessCoarseLocationPermissionRule = GrantPermissionRule.grant(
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION);
|
||||
|
||||
@Rule
|
||||
public GrantPermissionRule writeExternalStoragePermissionRule = GrantPermissionRule.grant(
|
||||
Manifest.permission.WRITE_EXTERNAL_STORAGE);
|
||||
|
||||
@Test
|
||||
public void bottomNavFlavorCheck() {
|
||||
onView(withText(R.string.main_menu__updates)).check(matches(isDisplayed()));
|
||||
onView(withText(R.string.menu_settings)).check(matches(isDisplayed()));
|
||||
onView(withText("THIS SHOULD NOT SHOW UP ANYWHERE!!!")).check(doesNotExist());
|
||||
|
||||
assertTrue(BuildConfig.FLAVOR.startsWith("full") || BuildConfig.FLAVOR.startsWith("basic"));
|
||||
|
||||
if (BuildConfig.FLAVOR.startsWith("basic")) {
|
||||
onView(withText(R.string.main_menu__latest_apps)).check(matches(isDisplayed()));
|
||||
onView(withText(R.string.main_menu__categories)).check(doesNotExist());
|
||||
onView(withText(R.string.main_menu__swap_nearby)).check(doesNotExist());
|
||||
}
|
||||
|
||||
if (BuildConfig.FLAVOR.startsWith("full")) {
|
||||
onView(withText(R.string.main_menu__latest_apps)).check(matches(isDisplayed()));
|
||||
onView(withText(R.string.main_menu__categories)).check(matches(isDisplayed()));
|
||||
onView(withText(R.string.main_menu__swap_nearby)).check(matches(isDisplayed()));
|
||||
}
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void showSettings() {
|
||||
ViewInteraction settingsBottonNavButton = onView(
|
||||
allOf(withText(R.string.menu_settings), isDisplayed()));
|
||||
settingsBottonNavButton.perform(click());
|
||||
onView(withText(R.string.preference_manage_installed_apps)).check(matches(isDisplayed()));
|
||||
if (BuildConfig.FLAVOR.startsWith("basic") && BuildConfig.APPLICATION_ID.endsWith(".debug")) {
|
||||
// TODO fix me by sorting out the flavor applicationId for debug builds in app/build.gradle
|
||||
Log.i(TAG, "Skipping the remainder of showSettings test because it just crashes on basic .debug builds");
|
||||
return;
|
||||
}
|
||||
ViewInteraction manageInstalledAppsButton = onView(
|
||||
allOf(withText(R.string.preference_manage_installed_apps), isDisplayed()));
|
||||
manageInstalledAppsButton.perform(click());
|
||||
onView(withText(R.string.installed_apps__activity_title)).check(matches(isDisplayed()));
|
||||
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());
|
||||
|
||||
onView(withText(R.string.menu_manage)).perform(click());
|
||||
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());
|
||||
|
||||
manageInstalledAppsButton.perform(click());
|
||||
onView(withText(R.string.installed_apps__activity_title)).check(matches(isDisplayed()));
|
||||
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());
|
||||
|
||||
onView(withText(R.string.menu_manage)).perform(click());
|
||||
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());
|
||||
|
||||
onView(withText(R.string.about_title)).perform(click());
|
||||
onView(withId(R.id.version)).check(matches(isDisplayed()));
|
||||
onView(withId(R.id.ok_button)).perform(click());
|
||||
|
||||
onView(withId(android.R.id.list_container)).perform(swipeUp()).perform(swipeUp()).perform(swipeUp());
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void showUpdates() {
|
||||
ViewInteraction updatesBottonNavButton = onView(allOf(withText(R.string.main_menu__updates), isDisplayed()));
|
||||
updatesBottonNavButton.perform(click());
|
||||
onView(withText(R.string.main_menu__updates)).check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void startSwap() {
|
||||
if (!BuildConfig.FLAVOR.startsWith("full")) {
|
||||
return;
|
||||
}
|
||||
ViewInteraction nearbyBottonNavButton = onView(
|
||||
allOf(withText(R.string.main_menu__swap_nearby), isDisplayed()));
|
||||
nearbyBottonNavButton.perform(click());
|
||||
ViewInteraction findPeopleButton = onView(
|
||||
allOf(withId(R.id.find_people_button), withText(R.string.nearby_splash__find_people_button),
|
||||
isDisplayed()));
|
||||
findPeopleButton.perform(click());
|
||||
onView(withText(R.string.swap_send_fdroid)).check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void showCategories() {
|
||||
if (!BuildConfig.FLAVOR.startsWith("full")) {
|
||||
return;
|
||||
}
|
||||
onView(allOf(withText(R.string.menu_settings), isDisplayed())).perform(click());
|
||||
onView(allOf(withText(R.string.main_menu__categories), isDisplayed())).perform(click());
|
||||
onView(allOf(withId(R.id.swipe_to_refresh), isDisplayed()))
|
||||
.perform(swipeDown())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeRight())
|
||||
.perform(swipeLeft())
|
||||
.perform(swipeLeft())
|
||||
.perform(swipeLeft())
|
||||
.perform(swipeLeft())
|
||||
.perform(click());
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void showLatest() {
|
||||
if (!BuildConfig.FLAVOR.startsWith("full")) {
|
||||
return;
|
||||
}
|
||||
onView(Matchers.<View>instanceOf(StatusBanner.class)).check(matches(not(isDisplayed())));
|
||||
onView(allOf(withText(R.string.menu_settings), isDisplayed())).perform(click());
|
||||
onView(allOf(withText(R.string.main_menu__latest_apps), isDisplayed())).perform(click());
|
||||
onView(allOf(withId(R.id.swipe_to_refresh), isDisplayed()))
|
||||
.perform(swipeDown())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeUp())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeDown())
|
||||
.perform(swipeDown())
|
||||
.perform(click());
|
||||
}
|
||||
|
||||
@LargeTest
|
||||
@Test
|
||||
public void showSearch() {
|
||||
onView(allOf(withText(R.string.menu_settings), isDisplayed())).perform(click());
|
||||
onView(withId(R.id.fab_search)).check(doesNotExist());
|
||||
if (!BuildConfig.FLAVOR.startsWith("full")) {
|
||||
return;
|
||||
}
|
||||
onView(allOf(withText(R.string.main_menu__latest_apps), isDisplayed())).perform(click());
|
||||
onView(allOf(withId(R.id.fab_search), isDisplayed())).perform(click());
|
||||
onView(withId(R.id.sort)).check(matches(isDisplayed()));
|
||||
onView(allOf(withId(R.id.search), isDisplayed()))
|
||||
.perform(click())
|
||||
.perform(typeText("test"));
|
||||
onView(allOf(withId(R.id.sort), isDisplayed())).perform(click());
|
||||
}
|
||||
}
|
@ -1,372 +0,0 @@
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Replacer for the netstat utility, by reading the /proc filesystem it can find out the
|
||||
* open connections of the system
|
||||
* From http://www.ussg.iu.edu/hypermail/linux/kernel/0409.1/2166.html :
|
||||
* It will first list all listening TCP sockets, and next list all established
|
||||
* TCP connections. A typical entry of /proc/net/tcp would look like this (split
|
||||
* up into 3 parts because of the length of the line):
|
||||
* <p>
|
||||
* 46: 010310AC:9C4C 030310AC:1770 01
|
||||
* | | | | | |--> connection state
|
||||
* | | | | |------> remote TCP port number
|
||||
* | | | |-------------> remote IPv4 address
|
||||
* | | |--------------------> local TCP port number
|
||||
* | |---------------------------> local IPv4 address
|
||||
* |----------------------------------> number of entry
|
||||
* <p>
|
||||
* 00000150:00000000 01:00000019 00000000
|
||||
* | | | | |--> number of unrecovered RTO timeouts
|
||||
* | | | |----------> number of jiffies until timer expires
|
||||
* | | |----------------> timer_active (see below)
|
||||
* | |----------------------> receive-queue
|
||||
* |-------------------------------> transmit-queue
|
||||
* <p>
|
||||
* 1000 0 54165785 4 cd1e6040 25 4 27 3 -1
|
||||
* | | | | | | | | | |--> slow start size threshold,
|
||||
* | | | | | | | | | or -1 if the treshold
|
||||
* | | | | | | | | | is >= 0xFFFF
|
||||
* | | | | | | | | |----> sending congestion window
|
||||
* | | | | | | | |-------> (ack.quick<<1)|ack.pingpong
|
||||
* | | | | | | |---------> Predicted tick of soft clock
|
||||
* | | | | | | (delayed ACK control data)
|
||||
* | | | | | |------------> retransmit timeout
|
||||
* | | | | |------------------> location of socket in memory
|
||||
* | | | |-----------------------> socket reference count
|
||||
* | | |-----------------------------> inode
|
||||
* | |----------------------------------> unanswered 0-window probes
|
||||
* |---------------------------------------------> uid
|
||||
*
|
||||
* @author Ciprian Dobre
|
||||
*/
|
||||
public class Netstat {
|
||||
|
||||
/**
|
||||
* Possible values for states in /proc/net/tcp
|
||||
*/
|
||||
private static final String[] STATES = {
|
||||
"ESTBLSH", "SYNSENT", "SYNRECV", "FWAIT1", "FWAIT2", "TMEWAIT",
|
||||
"CLOSED", "CLSWAIT", "LASTACK", "LISTEN", "CLOSING", "UNKNOWN",
|
||||
};
|
||||
/**
|
||||
* Pattern used when parsing through /proc/net/tcp
|
||||
*/
|
||||
private static final Pattern NET_PATTERN = Pattern.compile(
|
||||
"\\d+:\\s+([\\dA-F]+):([\\dA-F]+)\\s+([\\dA-F]+):([\\dA-F]+)\\s+([\\dA-F]+)\\s+" +
|
||||
"[\\dA-F]+:[\\dA-F]+\\s+[\\dA-F]+:[\\dA-F]+\\s+[\\dA-F]+\\s+([\\d]+)\\s+[\\d]+\\s+([\\d]+)");
|
||||
|
||||
/**
|
||||
* Utility method that converts an address from a hex representation as founded in /proc to String representation
|
||||
*/
|
||||
private static String getAddress(final String hexa) {
|
||||
try {
|
||||
// first let's convert the address to Integer
|
||||
final long v = Long.parseLong(hexa, 16);
|
||||
// in /proc the order is little endian and java uses big endian order we also need to invert the order
|
||||
final long adr = (v >>> 24) | (v << 24) |
|
||||
((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00);
|
||||
// and now it's time to output the result
|
||||
return ((adr >> 24) & 0xff) + "." + ((adr >> 16) & 0xff) + "." + ((adr >> 8) & 0xff) + "." + (adr & 0xff);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return "0.0.0.0"; // NOPMD
|
||||
}
|
||||
}
|
||||
|
||||
private static int getInt16(final String hexa) {
|
||||
try {
|
||||
return Integer.parseInt(hexa, 16);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
private static String getPName(final int pid) {
|
||||
final Pattern pattern = Pattern.compile("Name:\\s*(\\S+)");
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(new FileReader("/proc/" + pid + "/status"));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
final Matcher matcher = pattern.matcher(line);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
} catch (Throwable t) {
|
||||
// ignored
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Method used to question for the connections currently openned
|
||||
*
|
||||
* @return The list of connections (as Connection objects)
|
||||
*/
|
||||
public static List<Connection> getConnections() {
|
||||
|
||||
final ArrayList<Connection> net = new ArrayList<>();
|
||||
|
||||
// read from /proc/net/tcp the list of currently openned socket connections
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(new FileReader("/proc/net/tcp"));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) { // NOPMD
|
||||
Matcher matcher = NET_PATTERN.matcher(line);
|
||||
if (matcher.find()) {
|
||||
final Connection c = new Connection();
|
||||
c.setProtocol(Connection.TCP_CONNECTION);
|
||||
net.add(c);
|
||||
final String localPortHexa = matcher.group(2);
|
||||
final String remoteAddressHexa = matcher.group(3);
|
||||
final String remotePortHexa = matcher.group(4);
|
||||
final String statusHexa = matcher.group(5);
|
||||
//final String uid = matcher.group(6);
|
||||
//final String inode = matcher.group(7);
|
||||
c.setLocalPort(getInt16(localPortHexa));
|
||||
c.setRemoteAddress(getAddress(remoteAddressHexa));
|
||||
c.setRemotePort(getInt16(remotePortHexa));
|
||||
try {
|
||||
c.setStatus(STATES[Integer.parseInt(statusHexa, 16) - 1]);
|
||||
} catch (Exception ex) {
|
||||
c.setStatus(STATES[11]); // unknown
|
||||
}
|
||||
c.setPID(-1); // unknown
|
||||
c.setPName("UNKNOWN");
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
} catch (Throwable t) { // NOPMD
|
||||
// ignored
|
||||
}
|
||||
|
||||
// read from /proc/net/udp the list of currently openned socket connections
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(new FileReader("/proc/net/udp"));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) { // NOPMD
|
||||
Matcher matcher = NET_PATTERN.matcher(line);
|
||||
if (matcher.find()) {
|
||||
final Connection c = new Connection();
|
||||
c.setProtocol(Connection.UDP_CONNECTION);
|
||||
net.add(c);
|
||||
final String localPortHexa = matcher.group(2);
|
||||
final String remoteAddressHexa = matcher.group(3);
|
||||
final String remotePortHexa = matcher.group(4);
|
||||
final String statusHexa = matcher.group(5);
|
||||
//final String uid = matcher.group(6);
|
||||
//final String inode = matcher.group(7);
|
||||
c.setLocalPort(getInt16(localPortHexa));
|
||||
c.setRemoteAddress(getAddress(remoteAddressHexa));
|
||||
c.setRemotePort(getInt16(remotePortHexa));
|
||||
try {
|
||||
c.setStatus(STATES[Integer.parseInt(statusHexa, 16) - 1]);
|
||||
} catch (Exception ex) {
|
||||
c.setStatus(STATES[11]); // unknown
|
||||
}
|
||||
c.setPID(-1); // unknown
|
||||
c.setPName("UNKNOWN");
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
} catch (Throwable t) { // NOPMD
|
||||
// ignored
|
||||
}
|
||||
|
||||
// read from /proc/net/raw the list of currently openned socket connections
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(new FileReader("/proc/net/raw"));
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) { // NOPMD
|
||||
Matcher matcher = NET_PATTERN.matcher(line);
|
||||
if (matcher.find()) {
|
||||
final Connection c = new Connection();
|
||||
c.setProtocol(Connection.RAW_CONNECTION);
|
||||
net.add(c);
|
||||
//final String localAddressHexa = matcher.group(1);
|
||||
final String localPortHexa = matcher.group(2);
|
||||
final String remoteAddressHexa = matcher.group(3);
|
||||
final String remotePortHexa = matcher.group(4);
|
||||
final String statusHexa = matcher.group(5);
|
||||
//final String uid = matcher.group(6);
|
||||
//final String inode = matcher.group(7);
|
||||
c.setLocalPort(getInt16(localPortHexa));
|
||||
c.setRemoteAddress(getAddress(remoteAddressHexa));
|
||||
c.setRemotePort(getInt16(remotePortHexa));
|
||||
try {
|
||||
c.setStatus(STATES[Integer.parseInt(statusHexa, 16) - 1]);
|
||||
} catch (Exception ex) {
|
||||
c.setStatus(STATES[11]); // unknown
|
||||
}
|
||||
c.setPID(-1); // unknown
|
||||
c.setPName("UNKNOWN");
|
||||
}
|
||||
}
|
||||
in.close();
|
||||
} catch (Throwable t) { // NOPMD
|
||||
// ignored
|
||||
}
|
||||
return net;
|
||||
}
|
||||
|
||||
/**
|
||||
* Informations about a given connection
|
||||
*
|
||||
* @author Ciprian Dobre
|
||||
*/
|
||||
public static class Connection {
|
||||
|
||||
/**
|
||||
* Types of connection protocol
|
||||
***/
|
||||
public static final byte TCP_CONNECTION = 0;
|
||||
public static final byte UDP_CONNECTION = 1;
|
||||
public static final byte RAW_CONNECTION = 2;
|
||||
/**
|
||||
* <code>serialVersionUID</code>
|
||||
*/
|
||||
private static final long serialVersionUID = 1988671591829311032L;
|
||||
/**
|
||||
* The protocol of the connection (can be tcp, udp or raw)
|
||||
*/
|
||||
protected byte protocol;
|
||||
|
||||
/**
|
||||
* The owner of the connection (username)
|
||||
*/
|
||||
protected String powner;
|
||||
|
||||
/**
|
||||
* The pid of the owner process
|
||||
*/
|
||||
protected int pid;
|
||||
|
||||
/**
|
||||
* The name of the program owning the connection
|
||||
*/
|
||||
protected String pname;
|
||||
|
||||
/**
|
||||
* Local port
|
||||
*/
|
||||
protected int localPort;
|
||||
|
||||
/**
|
||||
* Remote address of the connection
|
||||
*/
|
||||
protected String remoteAddress;
|
||||
|
||||
/**
|
||||
* Remote port
|
||||
*/
|
||||
protected int remotePort;
|
||||
|
||||
/**
|
||||
* Status of the connection
|
||||
*/
|
||||
protected String status;
|
||||
|
||||
public final byte getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
public final void setProtocol(final byte protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public final String getProtocolAsString() {
|
||||
switch (protocol) {
|
||||
case TCP_CONNECTION:
|
||||
return "TCP";
|
||||
case UDP_CONNECTION:
|
||||
return "UDP";
|
||||
case RAW_CONNECTION:
|
||||
return "RAW";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
public final String getPOwner() {
|
||||
return powner;
|
||||
}
|
||||
|
||||
public final void setPOwner(final String owner) {
|
||||
this.powner = owner;
|
||||
}
|
||||
|
||||
public final int getPID() {
|
||||
return pid;
|
||||
}
|
||||
|
||||
public final void setPID(final int pid) {
|
||||
this.pid = pid;
|
||||
}
|
||||
|
||||
public final String getPName() {
|
||||
return pname;
|
||||
}
|
||||
|
||||
public final void setPName(final String pname) {
|
||||
this.pname = pname;
|
||||
}
|
||||
|
||||
public final int getLocalPort() {
|
||||
return localPort;
|
||||
}
|
||||
|
||||
public final void setLocalPort(final int localPort) {
|
||||
this.localPort = localPort;
|
||||
}
|
||||
|
||||
public final String getRemoteAddress() {
|
||||
return remoteAddress;
|
||||
}
|
||||
|
||||
public final void setRemoteAddress(final String remoteAddress) {
|
||||
this.remoteAddress = remoteAddress;
|
||||
}
|
||||
|
||||
public final int getRemotePort() {
|
||||
return remotePort;
|
||||
}
|
||||
|
||||
public final void setRemotePort(final int remotePort) {
|
||||
this.remotePort = remotePort;
|
||||
}
|
||||
|
||||
public final String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public final void setStatus(final String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
StringBuffer buf = new StringBuffer();
|
||||
buf.append("[Prot=").append(getProtocolAsString());
|
||||
buf.append(",POwner=").append(powner);
|
||||
buf.append(",PID=").append(pid);
|
||||
buf.append(",PName=").append(pname);
|
||||
buf.append(",LPort=").append(localPort);
|
||||
buf.append(",RAddress=").append(remoteAddress);
|
||||
buf.append(",RPort=").append(remotePort);
|
||||
buf.append(",Status=").append(status);
|
||||
buf.append("]");
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* @see <a href="https://artemzin.com/blog/easiest-way-to-give-set_animation_scale-permission-for-your-ui-tests-on-android/>EASIEST WAY TO GIVE SET_ANIMATION_SCALE PERMISSION FOR YOUR UI TESTS ON ANDROID</a>
|
||||
* @see <a href="https://gist.github.com/xrigau/11284124>Disable animations for Espresso tests</a>
|
||||
*/
|
||||
class SystemAnimations {
|
||||
public static final String TAG = "SystemAnimations";
|
||||
|
||||
private static final float DISABLED = 0.0f;
|
||||
private static final float DEFAULT = 1.0f;
|
||||
|
||||
static void disableAll(Context context) {
|
||||
int permStatus = context.checkCallingOrSelfPermission(Manifest.permission.SET_ANIMATION_SCALE);
|
||||
if (permStatus == PackageManager.PERMISSION_GRANTED) {
|
||||
Log.i(TAG, "Manifest.permission.SET_ANIMATION_SCALE PERMISSION_GRANTED");
|
||||
setSystemAnimationsScale(DISABLED);
|
||||
} else {
|
||||
Log.i(TAG, "Disabling Manifest.permission.SET_ANIMATION_SCALE failed: " + permStatus);
|
||||
}
|
||||
}
|
||||
|
||||
static void enableAll(Context context) {
|
||||
int permStatus = context.checkCallingOrSelfPermission(Manifest.permission.SET_ANIMATION_SCALE);
|
||||
if (permStatus == PackageManager.PERMISSION_GRANTED) {
|
||||
Log.i(TAG, "Manifest.permission.SET_ANIMATION_SCALE PERMISSION_GRANTED");
|
||||
setSystemAnimationsScale(DEFAULT);
|
||||
} else {
|
||||
Log.i(TAG, "Enabling Manifest.permission.SET_ANIMATION_SCALE failed: " + permStatus);
|
||||
}
|
||||
}
|
||||
|
||||
private static void setSystemAnimationsScale(float animationScale) {
|
||||
try {
|
||||
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
|
||||
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
|
||||
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
|
||||
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
|
||||
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
|
||||
Method setAnimationScales = windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class);
|
||||
Method getAnimationScales = windowManagerClazz.getDeclaredMethod("getAnimationScales");
|
||||
|
||||
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
|
||||
Object windowManagerObj = asInterface.invoke(null, windowManagerBinder);
|
||||
float[] currentScales = (float[]) getAnimationScales.invoke(windowManagerObj);
|
||||
for (int i = 0; i < currentScales.length; i++) {
|
||||
currentScales[i] = animationScale;
|
||||
}
|
||||
setAnimationScales.invoke(windowManagerObj, new Object[]{currentScales});
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG, "Could not change animation scale to " + animationScale + " :'(");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,156 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2013 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid;
|
||||
|
||||
import androidx.test.uiautomator.UiDevice;
|
||||
import androidx.test.uiautomator.UiObject;
|
||||
import androidx.test.uiautomator.UiObjectNotFoundException;
|
||||
import androidx.test.uiautomator.UiSelector;
|
||||
import androidx.test.uiautomator.UiWatcher;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@SuppressWarnings("MemberName")
|
||||
public class UiWatchers {
|
||||
private static final String LOG_TAG = UiWatchers.class.getSimpleName();
|
||||
private final List<String> mErrors = new ArrayList<String>();
|
||||
|
||||
/**
|
||||
* We can use the UiDevice registerWatcher to register a small script to be executed when the
|
||||
* framework is waiting for a control to appear. Waiting may be the cause of an unexpected
|
||||
* dialog on the screen and it is the time when the framework runs the registered watchers.
|
||||
* This is a sample watcher looking for ANR and crashes. it closes it and moves on. You should
|
||||
* create your own watchers and handle error logging properly for your type of tests.
|
||||
*/
|
||||
public void registerAnrAndCrashWatchers() {
|
||||
UiDevice.getInstance().registerWatcher("ANR", new UiWatcher() {
|
||||
@Override
|
||||
public boolean checkForCondition() {
|
||||
UiObject window = new UiObject(new UiSelector().className(
|
||||
"com.android.server.am.AppNotRespondingDialog"));
|
||||
String errorText = null;
|
||||
if (window.exists()) {
|
||||
try {
|
||||
errorText = window.getText();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
Log.e(LOG_TAG, "dialog gone?", e);
|
||||
}
|
||||
onAnrDetected(errorText);
|
||||
postHandler("Wait");
|
||||
return true; // triggered
|
||||
}
|
||||
return false; // no trigger
|
||||
}
|
||||
});
|
||||
// class names may have changed
|
||||
UiDevice.getInstance().registerWatcher("ANR2", new UiWatcher() {
|
||||
@Override
|
||||
public boolean checkForCondition() {
|
||||
UiObject window = new UiObject(new UiSelector().packageName("android")
|
||||
.textContains("isn't responding."));
|
||||
if (window.exists()) {
|
||||
String errorText = null;
|
||||
try {
|
||||
errorText = window.getText();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
Log.e(LOG_TAG, "dialog gone?", e);
|
||||
}
|
||||
onAnrDetected(errorText);
|
||||
postHandler("Wait");
|
||||
return true; // triggered
|
||||
}
|
||||
return false; // no trigger
|
||||
}
|
||||
});
|
||||
UiDevice.getInstance().registerWatcher("CRASH", new UiWatcher() {
|
||||
@Override
|
||||
public boolean checkForCondition() {
|
||||
UiObject window = new UiObject(new UiSelector().className(
|
||||
"com.android.server.am.AppErrorDialog"));
|
||||
if (window.exists()) {
|
||||
String errorText = null;
|
||||
try {
|
||||
errorText = window.getText();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
Log.e(LOG_TAG, "dialog gone?", e);
|
||||
}
|
||||
onCrashDetected(errorText);
|
||||
postHandler("OK");
|
||||
return true; // triggered
|
||||
}
|
||||
return false; // no trigger
|
||||
}
|
||||
});
|
||||
UiDevice.getInstance().registerWatcher("CRASH2", new UiWatcher() {
|
||||
@Override
|
||||
public boolean checkForCondition() {
|
||||
UiObject window = new UiObject(new UiSelector().packageName("android")
|
||||
.textContains("has stopped"));
|
||||
if (window.exists()) {
|
||||
String errorText = null;
|
||||
try {
|
||||
errorText = window.getText();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
Log.e(LOG_TAG, "dialog gone?", e);
|
||||
}
|
||||
onCrashDetected(errorText);
|
||||
postHandler("OK");
|
||||
return true; // triggered
|
||||
}
|
||||
return false; // no trigger
|
||||
}
|
||||
});
|
||||
Log.i(LOG_TAG, "Registered GUI Exception watchers");
|
||||
}
|
||||
|
||||
public void onAnrDetected(String errorText) {
|
||||
mErrors.add(errorText);
|
||||
}
|
||||
|
||||
public void onCrashDetected(String errorText) {
|
||||
mErrors.add(errorText);
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
mErrors.clear();
|
||||
}
|
||||
|
||||
public List<String> getErrors() {
|
||||
return Collections.unmodifiableList(mErrors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Current implementation ignores the exception and continues.
|
||||
*/
|
||||
public void postHandler(String buttonText) {
|
||||
// TODO: Add custom error logging here
|
||||
String formatedOutput = String.format("UI Exception Message: %-20s\n", UiDevice
|
||||
.getInstance().getCurrentPackageName());
|
||||
Log.e(LOG_TAG, formatedOutput);
|
||||
UiObject buttonOK = new UiObject(new UiSelector().text(buttonText).enabled(true));
|
||||
// sometimes it takes a while for the OK button to become enabled
|
||||
buttonOK.waitForExists(5000);
|
||||
try {
|
||||
buttonOK.click();
|
||||
} catch (UiObjectNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -4,8 +4,8 @@ import android.app.Instrumentation;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import android.support.test.InstrumentationRegistry;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.AssetUtils;
|
||||
|
@ -22,16 +22,17 @@ package org.fdroid.fdroid.installer;
|
||||
import android.app.Instrumentation;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.test.InstrumentationRegistry;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
|
||||
import org.fdroid.fdroid.AssetUtils;
|
||||
import org.fdroid.fdroid.RepoXMLHandler;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.compat.FileCompatTest;
|
||||
import org.fdroid.fdroid.data.Apk;
|
||||
import org.fdroid.fdroid.data.Repo;
|
||||
import org.fdroid.fdroid.data.RepoXMLHandler;
|
||||
import org.fdroid.fdroid.mock.RepoDetails;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@ -44,7 +45,6 @@ import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
@ -103,7 +103,7 @@ public class ApkVerifierTest {
|
||||
public void testNulls() {
|
||||
assertTrue(ApkVerifier.requestedPermissionsEqual(null, null));
|
||||
|
||||
String[] perms = new String[]{"Blah"};
|
||||
String[] perms = new String[] {"Blah"};
|
||||
assertFalse(ApkVerifier.requestedPermissionsEqual(perms, null));
|
||||
assertFalse(ApkVerifier.requestedPermissionsEqual(null, perms));
|
||||
}
|
||||
@ -113,7 +113,7 @@ public class ApkVerifierTest {
|
||||
Apk apk = new Apk();
|
||||
apk.packageName = "org.fdroid.permissions.sdk14";
|
||||
apk.targetSdkVersion = 14;
|
||||
ArrayList<String> noPrefixPermissionsList = new ArrayList<>(Arrays.asList(
|
||||
String[] noPrefixPermissions = new String[]{
|
||||
"AUTHENTICATE_ACCOUNTS",
|
||||
"MANAGE_ACCOUNTS",
|
||||
"READ_PROFILE",
|
||||
@ -129,13 +129,8 @@ public class ApkVerifierTest {
|
||||
"READ_SYNC_SETTINGS",
|
||||
"WRITE_SYNC_SETTINGS",
|
||||
"WRITE_CALL_LOG", // implied-permission!
|
||||
"READ_CALL_LOG" // implied-permission!
|
||||
));
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
noPrefixPermissionsList.add("android.permission.ACCESS_MEDIA_LOCATION");
|
||||
}
|
||||
String[] noPrefixPermissions = noPrefixPermissionsList.toArray(new String[0]);
|
||||
|
||||
"READ_CALL_LOG", // implied-permission!
|
||||
};
|
||||
for (int i = 0; i < noPrefixPermissions.length; i++) {
|
||||
noPrefixPermissions[i] = RepoXMLHandler.fdroidToAndroidPermission(noPrefixPermissions[i]);
|
||||
}
|
||||
@ -182,7 +177,7 @@ public class ApkVerifierTest {
|
||||
Apk apk = new Apk();
|
||||
apk.packageName = "org.fdroid.permissions.sdk14";
|
||||
apk.targetSdkVersion = 14;
|
||||
TreeSet<String> expectedSet = new TreeSet<>(Arrays.asList(
|
||||
apk.requestedPermissions = new String[]{
|
||||
"android.permission.AUTHENTICATE_ACCOUNTS",
|
||||
"android.permission.MANAGE_ACCOUNTS",
|
||||
"android.permission.READ_PROFILE",
|
||||
@ -198,12 +193,8 @@ public class ApkVerifierTest {
|
||||
"android.permission.READ_SYNC_SETTINGS",
|
||||
"android.permission.WRITE_SYNC_SETTINGS",
|
||||
"android.permission.WRITE_CALL_LOG", // implied-permission!
|
||||
"android.permission.READ_CALL_LOG"// implied-permission!
|
||||
));
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
expectedSet.add("android.permission.ACCESS_MEDIA_LOCATION");
|
||||
}
|
||||
apk.requestedPermissions = expectedSet.toArray(new String[0]);
|
||||
"android.permission.READ_CALL_LOG", // implied-permission!
|
||||
};
|
||||
|
||||
Uri uri = Uri.fromFile(sdk14Apk);
|
||||
|
||||
@ -299,7 +290,7 @@ public class ApkVerifierTest {
|
||||
public void testExtendedPerms() throws IOException,
|
||||
ApkVerifier.ApkPermissionUnequalException, ApkVerifier.ApkVerificationException {
|
||||
RepoDetails actualDetails = getFromFile(extendedPermsXml);
|
||||
HashSet<String> expectedSet = new HashSet<>(Arrays.asList(
|
||||
HashSet<String> expectedSet = new HashSet<>(Arrays.asList(new String[]{
|
||||
"android.permission.ACCESS_NETWORK_STATE",
|
||||
"android.permission.ACCESS_WIFI_STATE",
|
||||
"android.permission.INTERNET",
|
||||
@ -310,8 +301,8 @@ public class ApkVerifierTest {
|
||||
"android.permission.READ_CONTACTS",
|
||||
"android.permission.WRITE_CONTACTS",
|
||||
"android.permission.READ_CALENDAR",
|
||||
"android.permission.WRITE_CALENDAR"
|
||||
));
|
||||
"android.permission.WRITE_CALENDAR",
|
||||
}));
|
||||
if (Build.VERSION.SDK_INT <= 18) {
|
||||
expectedSet.add("android.permission.READ_EXTERNAL_STORAGE");
|
||||
expectedSet.add("android.permission.WRITE_EXTERNAL_STORAGE");
|
||||
@ -354,93 +345,6 @@ public class ApkVerifierTest {
|
||||
apkVerifier.verifyApk();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImpliedPerms() throws IOException {
|
||||
RepoDetails actualDetails = getFromFile(extendedPermsXml);
|
||||
TreeSet<String> expectedSet = new TreeSet<>(Arrays.asList(
|
||||
"android.permission.ACCESS_NETWORK_STATE",
|
||||
"android.permission.ACCESS_WIFI_STATE",
|
||||
"android.permission.INTERNET",
|
||||
"android.permission.READ_CALENDAR",
|
||||
"android.permission.READ_CONTACTS",
|
||||
"android.permission.READ_EXTERNAL_STORAGE",
|
||||
"android.permission.READ_SYNC_SETTINGS",
|
||||
"android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS",
|
||||
"android.permission.WRITE_CALENDAR",
|
||||
"android.permission.WRITE_CONTACTS",
|
||||
"android.permission.WRITE_EXTERNAL_STORAGE",
|
||||
"android.permission.WRITE_SYNC_SETTINGS",
|
||||
"org.dmfs.permission.READ_TASKS",
|
||||
"org.dmfs.permission.WRITE_TASKS"
|
||||
));
|
||||
if (Build.VERSION.SDK_INT <= 22) { // maxSdkVersion="22"
|
||||
expectedSet.addAll(Arrays.asList(
|
||||
"android.permission.AUTHENTICATE_ACCOUNTS",
|
||||
"android.permission.GET_ACCOUNTS",
|
||||
"android.permission.MANAGE_ACCOUNTS"
|
||||
));
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
expectedSet.add("android.permission.ACCESS_MEDIA_LOCATION");
|
||||
}
|
||||
Apk apk = actualDetails.apks.get(1);
|
||||
Log.i(TAG, "APK: " + apk.apkName);
|
||||
HashSet<String> actualSet = new HashSet<>(Arrays.asList(apk.requestedPermissions));
|
||||
for (String permission : expectedSet) {
|
||||
if (!actualSet.contains(permission)) {
|
||||
Log.i(TAG, permission + " in expected but not actual! (android-"
|
||||
+ Build.VERSION.SDK_INT + ")");
|
||||
}
|
||||
}
|
||||
for (String permission : actualSet) {
|
||||
if (!expectedSet.contains(permission)) {
|
||||
Log.i(TAG, permission + " in actual but not expected! (android-"
|
||||
+ Build.VERSION.SDK_INT + ")");
|
||||
}
|
||||
}
|
||||
String[] expectedPermissions = expectedSet.toArray(new String[expectedSet.size()]);
|
||||
assertTrue(ApkVerifier.requestedPermissionsEqual(expectedPermissions, apk.requestedPermissions));
|
||||
|
||||
expectedSet = new TreeSet<>(Arrays.asList(
|
||||
"android.permission.ACCESS_NETWORK_STATE",
|
||||
"android.permission.ACCESS_WIFI_STATE",
|
||||
"android.permission.AUTHENTICATE_ACCOUNTS",
|
||||
"android.permission.GET_ACCOUNTS",
|
||||
"android.permission.INTERNET",
|
||||
"android.permission.MANAGE_ACCOUNTS",
|
||||
"android.permission.READ_CALENDAR",
|
||||
"android.permission.READ_CONTACTS",
|
||||
"android.permission.READ_EXTERNAL_STORAGE",
|
||||
"android.permission.READ_SYNC_SETTINGS",
|
||||
"android.permission.WRITE_CALENDAR",
|
||||
"android.permission.WRITE_CONTACTS",
|
||||
"android.permission.WRITE_EXTERNAL_STORAGE",
|
||||
"android.permission.WRITE_SYNC_SETTINGS",
|
||||
"org.dmfs.permission.READ_TASKS",
|
||||
"org.dmfs.permission.WRITE_TASKS"
|
||||
));
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
expectedSet.add("android.permission.ACCESS_MEDIA_LOCATION");
|
||||
}
|
||||
expectedPermissions = expectedSet.toArray(new String[expectedSet.size()]);
|
||||
apk = actualDetails.apks.get(2);
|
||||
Log.i(TAG, "APK: " + apk.apkName);
|
||||
actualSet = new HashSet<>(Arrays.asList(apk.requestedPermissions));
|
||||
for (String permission : expectedSet) {
|
||||
if (!actualSet.contains(permission)) {
|
||||
Log.i(TAG, permission + " in expected but not actual! (android-"
|
||||
+ Build.VERSION.SDK_INT + ")");
|
||||
}
|
||||
}
|
||||
for (String permission : actualSet) {
|
||||
if (!expectedSet.contains(permission)) {
|
||||
Log.i(TAG, permission + " in actual but not expected! (android-"
|
||||
+ Build.VERSION.SDK_INT + ")");
|
||||
}
|
||||
}
|
||||
assertTrue(ApkVerifier.requestedPermissionsEqual(expectedPermissions, apk.requestedPermissions));
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private RepoDetails getFromFile(File indexFile) throws IOException {
|
||||
InputStream inputStream = null;
|
||||
|
@ -1,128 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.test.core.app.ApplicationProvider;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceListener;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class BonjourManagerTest {
|
||||
|
||||
private static final String NAME = "Robolectric-test";
|
||||
private static final String LOCALHOST = "localhost";
|
||||
private static final int PORT = 8888;
|
||||
|
||||
@Test
|
||||
public void testStartStop() throws InterruptedException {
|
||||
Context context = ApplicationProvider.getApplicationContext();
|
||||
|
||||
FDroidApp.ipAddressString = LOCALHOST;
|
||||
FDroidApp.port = PORT;
|
||||
|
||||
final CountDownLatch addedLatch = new CountDownLatch(1);
|
||||
final CountDownLatch resolvedLatch = new CountDownLatch(1);
|
||||
final CountDownLatch removedLatch = new CountDownLatch(1);
|
||||
BonjourManager.start(context, NAME, false,
|
||||
new ServiceListener() {
|
||||
@Override
|
||||
public void serviceAdded(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service added: " + serviceEvent.getInfo());
|
||||
if (NAME.equals(serviceEvent.getName())) {
|
||||
addedLatch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceRemoved(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service removed: " + serviceEvent.getInfo());
|
||||
removedLatch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceResolved(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service resolved: " + serviceEvent.getInfo());
|
||||
if (NAME.equals(serviceEvent.getName())) {
|
||||
resolvedLatch.countDown();
|
||||
}
|
||||
}
|
||||
}, getBlankServiceListener());
|
||||
BonjourManager.setVisible(context, true);
|
||||
assertTrue(addedLatch.await(30, TimeUnit.SECONDS));
|
||||
assertTrue(resolvedLatch.await(30, TimeUnit.SECONDS));
|
||||
BonjourManager.setVisible(context, false);
|
||||
assertTrue(removedLatch.await(30, TimeUnit.SECONDS));
|
||||
BonjourManager.stop(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestart() throws InterruptedException {
|
||||
Context context = ApplicationProvider.getApplicationContext();
|
||||
|
||||
FDroidApp.ipAddressString = LOCALHOST;
|
||||
FDroidApp.port = PORT;
|
||||
|
||||
BonjourManager.start(context, NAME, false, getBlankServiceListener(), getBlankServiceListener());
|
||||
|
||||
final CountDownLatch addedLatch = new CountDownLatch(1);
|
||||
final CountDownLatch resolvedLatch = new CountDownLatch(1);
|
||||
final CountDownLatch removedLatch = new CountDownLatch(1);
|
||||
BonjourManager.restart(context, NAME, false,
|
||||
new ServiceListener() {
|
||||
@Override
|
||||
public void serviceAdded(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service added: " + serviceEvent.getInfo());
|
||||
if (NAME.equals(serviceEvent.getName())) {
|
||||
addedLatch.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceRemoved(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service removed: " + serviceEvent.getInfo());
|
||||
removedLatch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceResolved(ServiceEvent serviceEvent) {
|
||||
System.out.println("Service resolved: " + serviceEvent.getInfo());
|
||||
if (NAME.equals(serviceEvent.getName())) {
|
||||
resolvedLatch.countDown();
|
||||
}
|
||||
}
|
||||
}, getBlankServiceListener());
|
||||
BonjourManager.setVisible(context, true);
|
||||
assertTrue(addedLatch.await(30, TimeUnit.SECONDS));
|
||||
assertTrue(resolvedLatch.await(30, TimeUnit.SECONDS));
|
||||
BonjourManager.setVisible(context, false);
|
||||
assertTrue(removedLatch.await(30, TimeUnit.SECONDS));
|
||||
BonjourManager.stop(context);
|
||||
}
|
||||
|
||||
private ServiceListener getBlankServiceListener() {
|
||||
return new ServiceListener() {
|
||||
@Override
|
||||
public void serviceAdded(ServiceEvent serviceEvent) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceRemoved(ServiceEvent serviceEvent) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceResolved(ServiceEvent serviceEvent) {
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
@ -1,192 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
|
||||
import androidx.test.core.app.ApplicationProvider;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
import android.util.Log;
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.Netstat;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
@LargeTest
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
public class LocalHTTPDManagerTest {
|
||||
private static final String TAG = "LocalHTTPDManagerTest";
|
||||
|
||||
private Context context;
|
||||
private LocalBroadcastManager lbm;
|
||||
|
||||
private static final String LOCALHOST = "localhost";
|
||||
private static final int PORT = 8888;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
context = ApplicationProvider.getApplicationContext();
|
||||
lbm = LocalBroadcastManager.getInstance(context);
|
||||
|
||||
FDroidApp.ipAddressString = LOCALHOST;
|
||||
FDroidApp.port = PORT;
|
||||
|
||||
for (Netstat.Connection connection : Netstat.getConnections()) { // NOPMD
|
||||
Log.i("LocalHTTPDManagerTest", "connection: " + connection.toString());
|
||||
}
|
||||
assertFalse(Utils.isServerSocketInUse(PORT));
|
||||
LocalHTTPDManager.stop(context);
|
||||
|
||||
for (Netstat.Connection connection : Netstat.getConnections()) { // NOPMD
|
||||
Log.i("LocalHTTPDManagerTest", "connection: " + connection.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
lbm.unregisterReceiver(startedReceiver);
|
||||
lbm.unregisterReceiver(stoppedReceiver);
|
||||
lbm.unregisterReceiver(errorReceiver);
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void testStartStop() throws InterruptedException {
|
||||
Log.i(TAG, "testStartStop");
|
||||
|
||||
final CountDownLatch startLatch = new CountDownLatch(1);
|
||||
BroadcastReceiver latchReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
startLatch.countDown();
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(latchReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STARTED));
|
||||
lbm.registerReceiver(stoppedReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STOPPED));
|
||||
lbm.registerReceiver(errorReceiver, new IntentFilter(LocalHTTPDManager.ACTION_ERROR));
|
||||
LocalHTTPDManager.start(context, false);
|
||||
assertTrue(startLatch.await(30, TimeUnit.SECONDS));
|
||||
assertTrue(Utils.isServerSocketInUse(PORT));
|
||||
assertTrue(Utils.canConnectToSocket(LOCALHOST, PORT));
|
||||
lbm.unregisterReceiver(latchReceiver);
|
||||
lbm.unregisterReceiver(stoppedReceiver);
|
||||
lbm.unregisterReceiver(errorReceiver);
|
||||
|
||||
final CountDownLatch stopLatch = new CountDownLatch(1);
|
||||
latchReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
stopLatch.countDown();
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(startedReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STARTED));
|
||||
lbm.registerReceiver(latchReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STOPPED));
|
||||
lbm.registerReceiver(errorReceiver, new IntentFilter(LocalHTTPDManager.ACTION_ERROR));
|
||||
LocalHTTPDManager.stop(context);
|
||||
assertTrue(stopLatch.await(30, TimeUnit.SECONDS));
|
||||
assertFalse(Utils.isServerSocketInUse(PORT));
|
||||
assertFalse(Utils.canConnectToSocket(LOCALHOST, PORT)); // if this is flaky, just remove it
|
||||
lbm.unregisterReceiver(latchReceiver);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testError() throws InterruptedException, IOException {
|
||||
Log.i("LocalHTTPDManagerTest", "testError");
|
||||
ServerSocket blockerSocket = new ServerSocket(PORT);
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
BroadcastReceiver latchReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
latch.countDown();
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(startedReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STARTED));
|
||||
lbm.registerReceiver(stoppedReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STOPPED));
|
||||
lbm.registerReceiver(latchReceiver, new IntentFilter(LocalHTTPDManager.ACTION_ERROR));
|
||||
LocalHTTPDManager.start(context, false);
|
||||
assertTrue(latch.await(30, TimeUnit.SECONDS));
|
||||
assertTrue(Utils.isServerSocketInUse(PORT));
|
||||
assertNotEquals(PORT, FDroidApp.port);
|
||||
assertFalse(Utils.isServerSocketInUse(FDroidApp.port));
|
||||
lbm.unregisterReceiver(latchReceiver);
|
||||
blockerSocket.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRestart() throws InterruptedException, IOException {
|
||||
Log.i("LocalHTTPDManagerTest", "testRestart");
|
||||
assertFalse(Utils.isServerSocketInUse(PORT));
|
||||
final CountDownLatch startLatch = new CountDownLatch(1);
|
||||
BroadcastReceiver latchReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
startLatch.countDown();
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(latchReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STARTED));
|
||||
lbm.registerReceiver(stoppedReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STOPPED));
|
||||
lbm.registerReceiver(errorReceiver, new IntentFilter(LocalHTTPDManager.ACTION_ERROR));
|
||||
LocalHTTPDManager.start(context, false);
|
||||
assertTrue(startLatch.await(30, TimeUnit.SECONDS));
|
||||
assertTrue(Utils.isServerSocketInUse(PORT));
|
||||
lbm.unregisterReceiver(latchReceiver);
|
||||
lbm.unregisterReceiver(stoppedReceiver);
|
||||
|
||||
final CountDownLatch restartLatch = new CountDownLatch(1);
|
||||
latchReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
restartLatch.countDown();
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(latchReceiver, new IntentFilter(LocalHTTPDManager.ACTION_STARTED));
|
||||
LocalHTTPDManager.restart(context, false);
|
||||
assertTrue(restartLatch.await(30, TimeUnit.SECONDS));
|
||||
lbm.unregisterReceiver(latchReceiver);
|
||||
}
|
||||
|
||||
private final BroadcastReceiver startedReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String message = intent.getStringExtra(Intent.EXTRA_TEXT);
|
||||
Log.i(TAG, "startedReceiver: " + message);
|
||||
fail();
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver stoppedReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String message = intent.getStringExtra(Intent.EXTRA_TEXT);
|
||||
Log.i(TAG, "stoppedReceiver: " + message);
|
||||
fail();
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver errorReceiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
String message = intent.getStringExtra(Intent.EXTRA_TEXT);
|
||||
Log.i(TAG, "errorReceiver: " + message);
|
||||
fail();
|
||||
}
|
||||
};
|
||||
}
|
@ -1,16 +1,12 @@
|
||||
|
||||
package org.fdroid.fdroid.net;
|
||||
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import org.fdroid.fdroid.ProgressListener;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.net.URL;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ -19,40 +15,25 @@ import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class HttpDownloaderTest {
|
||||
private static final String TAG = "HttpDownloaderTest";
|
||||
|
||||
static final String[] URLS;
|
||||
|
||||
// https://developer.android.com/reference/javax/net/ssl/SSLContext
|
||||
static {
|
||||
ArrayList<String> tempUrls = new ArrayList<>(Arrays.asList(
|
||||
"https://f-droid.org/repo/index-v1.jar",
|
||||
// sites that use SNI for HTTPS
|
||||
String[] urls = {
|
||||
"https://en.wikipedia.org/wiki/Index.html",
|
||||
"https://mirrors.kernel.org/debian/dists/stable/Release",
|
||||
"https://fdroid.tetaneutral.net/fdroid/repo/index-v1.jar",
|
||||
"https://ftp.fau.de/fdroid/repo/index-v1.jar",
|
||||
//"https://microg.org/fdroid/repo/index-v1.jar",
|
||||
"https://f-droid.org/repo/index.jar",
|
||||
// sites that use SNI for HTTPS
|
||||
"https://guardianproject.info/fdroid/repo/index.jar",
|
||||
//"https://microg.org/fdroid/repo/index.jar",
|
||||
//"https://grobox.de/fdroid/repo/index.jar",
|
||||
"https://guardianproject.info/fdroid/repo/index-v1.jar"
|
||||
));
|
||||
if (Build.VERSION.SDK_INT >= 22) {
|
||||
tempUrls.addAll(Arrays.asList(
|
||||
"https://en.wikipedia.org/wiki/Index.html", // no SNI but weird ipv6 lookup issues
|
||||
"https://mirror.cyberbits.eu/fdroid/repo/index-v1.jar" // TLSv1.2 only and SNI
|
||||
));
|
||||
}
|
||||
URLS = tempUrls.toArray(new String[tempUrls.size()]);
|
||||
}
|
||||
};
|
||||
|
||||
private boolean receivedProgress;
|
||||
|
||||
@Test
|
||||
public void downloadUninterruptedTest() throws IOException, InterruptedException {
|
||||
for (String urlString : URLS) {
|
||||
Log.i(TAG, "URL: " + urlString);
|
||||
Uri uri = Uri.parse(urlString);
|
||||
for (String urlString : urls) {
|
||||
URL url = new URL(urlString);
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(uri, destFile);
|
||||
HttpDownloader httpDownloader = new HttpDownloader(url, destFile);
|
||||
httpDownloader.download();
|
||||
assertTrue(destFile.exists());
|
||||
assertTrue(destFile.canRead());
|
||||
@ -65,12 +46,12 @@ public class HttpDownloaderTest {
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
String urlString = "https://f-droid.org/repo/index.jar";
|
||||
receivedProgress = false;
|
||||
Uri uri = Uri.parse(urlString);
|
||||
URL url = new URL(urlString);
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
final HttpDownloader httpDownloader = new HttpDownloader(uri, destFile);
|
||||
final HttpDownloader httpDownloader = new HttpDownloader(url, destFile);
|
||||
httpDownloader.setListener(new ProgressListener() {
|
||||
@Override
|
||||
public void onProgress(long bytesRead, long totalBytes) {
|
||||
public void onProgress(URL sourceUrl, int bytesRead, int totalBytes) {
|
||||
receivedProgress = true;
|
||||
}
|
||||
});
|
||||
@ -95,9 +76,9 @@ public class HttpDownloaderTest {
|
||||
|
||||
@Test
|
||||
public void downloadHttpBasicAuth() throws IOException, InterruptedException {
|
||||
Uri uri = Uri.parse("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
URL url = new URL("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(uri, destFile, "myusername", "supersecretpassword");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(url, destFile, "myusername", "supersecretpassword");
|
||||
httpDownloader.download();
|
||||
assertTrue(destFile.exists());
|
||||
assertTrue(destFile.canRead());
|
||||
@ -106,9 +87,9 @@ public class HttpDownloaderTest {
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void downloadHttpBasicAuthWrongPassword() throws IOException, InterruptedException {
|
||||
Uri uri = Uri.parse("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
URL url = new URL("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(uri, destFile, "myusername", "wrongpassword");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(url, destFile, "myusername", "wrongpassword");
|
||||
httpDownloader.download();
|
||||
assertFalse(destFile.exists());
|
||||
destFile.deleteOnExit();
|
||||
@ -116,9 +97,9 @@ public class HttpDownloaderTest {
|
||||
|
||||
@Test(expected = IOException.class)
|
||||
public void downloadHttpBasicAuthWrongUsername() throws IOException, InterruptedException {
|
||||
Uri uri = Uri.parse("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
URL url = new URL("https://httpbin.org/basic-auth/myusername/supersecretpassword");
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(uri, destFile, "wrongusername", "supersecretpassword");
|
||||
HttpDownloader httpDownloader = new HttpDownloader(url, destFile, "wrongusername", "supersecretpassword");
|
||||
httpDownloader.download();
|
||||
assertFalse(destFile.exists());
|
||||
destFile.deleteOnExit();
|
||||
@ -127,12 +108,12 @@ public class HttpDownloaderTest {
|
||||
@Test
|
||||
public void downloadThenCancel() throws IOException, InterruptedException {
|
||||
final CountDownLatch latch = new CountDownLatch(2);
|
||||
Uri uri = Uri.parse("https://f-droid.org/repo/index.jar");
|
||||
URL url = new URL("https://f-droid.org/repo/index.jar");
|
||||
File destFile = File.createTempFile("dl-", "");
|
||||
final HttpDownloader httpDownloader = new HttpDownloader(uri, destFile);
|
||||
final HttpDownloader httpDownloader = new HttpDownloader(url, destFile);
|
||||
httpDownloader.setListener(new ProgressListener() {
|
||||
@Override
|
||||
public void onProgress(long bytesRead, long totalBytes) {
|
||||
public void onProgress(URL sourceUrl, int bytesRead, int totalBytes) {
|
||||
receivedProgress = true;
|
||||
latch.countDown();
|
||||
}
|
||||
|
@ -1,203 +0,0 @@
|
||||
package org.fdroid.fdroid.updater;
|
||||
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.os.Looper;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import org.fdroid.fdroid.BuildConfig;
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.Hasher;
|
||||
import org.fdroid.fdroid.IndexUpdater;
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.data.Apk;
|
||||
import org.fdroid.fdroid.data.ApkProvider;
|
||||
import org.fdroid.fdroid.data.App;
|
||||
import org.fdroid.fdroid.data.AppProvider;
|
||||
import org.fdroid.fdroid.data.Repo;
|
||||
import org.fdroid.fdroid.data.RepoProvider;
|
||||
import org.fdroid.fdroid.data.Schema;
|
||||
import org.fdroid.fdroid.nearby.LocalHTTPD;
|
||||
import org.fdroid.fdroid.nearby.LocalRepoKeyStore;
|
||||
import org.fdroid.fdroid.nearby.LocalRepoManager;
|
||||
import org.fdroid.fdroid.nearby.LocalRepoService;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
import java.security.cert.Certificate;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@LargeTest
|
||||
public class SwapRepoEmulatorTest {
|
||||
public static final String TAG = "SwapRepoEmulatorTest";
|
||||
|
||||
/**
|
||||
* @see org.fdroid.fdroid.nearby.WifiStateChangeService.WifiInfoThread#run()
|
||||
*/
|
||||
@Ignore
|
||||
@Test
|
||||
public void testSwap()
|
||||
throws IOException, LocalRepoKeyStore.InitException, IndexUpdater.UpdateException, InterruptedException {
|
||||
Looper.prepare();
|
||||
LocalHTTPD localHttpd = null;
|
||||
try {
|
||||
Log.i(TAG, "REPO: " + FDroidApp.repo);
|
||||
final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
|
||||
Preferences.setupForTests(context);
|
||||
|
||||
FDroidApp.initWifiSettings();
|
||||
assertNull(FDroidApp.repo.address);
|
||||
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
while (FDroidApp.repo.address == null) {
|
||||
try {
|
||||
Log.i(TAG, "Waiting for IP address... " + FDroidApp.repo.address);
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
latch.countDown();
|
||||
}
|
||||
}.start();
|
||||
latch.await(10, TimeUnit.MINUTES);
|
||||
assertNotNull(FDroidApp.repo.address);
|
||||
|
||||
LocalRepoService.runProcess(context, new String[]{context.getPackageName()});
|
||||
Log.i(TAG, "REPO: " + FDroidApp.repo);
|
||||
File indexJarFile = LocalRepoManager.get(context).getIndexJar();
|
||||
assertTrue(indexJarFile.isFile());
|
||||
|
||||
localHttpd = new LocalHTTPD(
|
||||
context,
|
||||
null,
|
||||
FDroidApp.port,
|
||||
LocalRepoManager.get(context).getWebRoot(),
|
||||
false);
|
||||
localHttpd.start();
|
||||
Thread.sleep(100); // give the server some tine to start.
|
||||
assertTrue(localHttpd.isAlive());
|
||||
|
||||
LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context);
|
||||
Certificate localCert = localRepoKeyStore.getCertificate();
|
||||
String signingCert = Hasher.hex(localCert);
|
||||
assertFalse(TextUtils.isEmpty(signingCert));
|
||||
assertFalse(TextUtils.isEmpty(Utils.calcFingerprint(localCert)));
|
||||
|
||||
Repo repoToDelete = RepoProvider.Helper.findByAddress(context, FDroidApp.repo.address);
|
||||
while (repoToDelete != null) {
|
||||
Log.d(TAG, "Removing old test swap repo matching this one: " + repoToDelete.address);
|
||||
RepoProvider.Helper.remove(context, repoToDelete.getId());
|
||||
repoToDelete = RepoProvider.Helper.findByAddress(context, FDroidApp.repo.address);
|
||||
}
|
||||
|
||||
ContentValues values = new ContentValues(4);
|
||||
values.put(Schema.RepoTable.Cols.SIGNING_CERT, signingCert);
|
||||
values.put(Schema.RepoTable.Cols.ADDRESS, FDroidApp.repo.address);
|
||||
values.put(Schema.RepoTable.Cols.NAME, FDroidApp.repo.name);
|
||||
values.put(Schema.RepoTable.Cols.IS_SWAP, true);
|
||||
final String lastEtag = UUID.randomUUID().toString();
|
||||
values.put(Schema.RepoTable.Cols.LAST_ETAG, lastEtag);
|
||||
RepoProvider.Helper.insert(context, values);
|
||||
Repo repo = RepoProvider.Helper.findByAddress(context, FDroidApp.repo.address);
|
||||
assertTrue(repo.isSwap);
|
||||
assertNotEquals(-1, repo.getId());
|
||||
assertTrue(repo.name.startsWith(FDroidApp.repo.name));
|
||||
assertEquals(lastEtag, repo.lastetag);
|
||||
assertNull(repo.lastUpdated);
|
||||
|
||||
assertTrue(isPortInUse(FDroidApp.ipAddressString, FDroidApp.port));
|
||||
Thread.sleep(100);
|
||||
IndexUpdater updater = new IndexUpdater(context, repo);
|
||||
updater.update();
|
||||
assertTrue(updater.hasChanged());
|
||||
|
||||
repo = RepoProvider.Helper.findByAddress(context, FDroidApp.repo.address);
|
||||
final Date lastUpdated = repo.lastUpdated;
|
||||
assertTrue("repo lastUpdated should be updated", new Date(2019, 5, 13).compareTo(repo.lastUpdated) > 0);
|
||||
|
||||
App app = AppProvider.Helper.findSpecificApp(context.getContentResolver(),
|
||||
context.getPackageName(), repo.getId());
|
||||
assertEquals(context.getPackageName(), app.packageName);
|
||||
|
||||
List<Apk> apks = ApkProvider.Helper.findByRepo(context, repo, Schema.ApkTable.Cols.ALL);
|
||||
assertEquals(1, apks.size());
|
||||
for (Apk apk : apks) {
|
||||
Log.i(TAG, "Apk: " + apk);
|
||||
assertEquals(context.getPackageName(), apk.packageName);
|
||||
assertEquals(BuildConfig.VERSION_NAME, apk.versionName);
|
||||
assertEquals(BuildConfig.VERSION_CODE, apk.versionCode);
|
||||
assertEquals(app.repoId, apk.repoId);
|
||||
}
|
||||
|
||||
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
|
||||
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
|
||||
List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(mainIntent, 0);
|
||||
HashSet<String> packageNames = new HashSet<>();
|
||||
for (ResolveInfo resolveInfo : resolveInfoList) {
|
||||
if (!isSystemPackage(resolveInfo)) {
|
||||
Log.i(TAG, "resolveInfo: " + resolveInfo);
|
||||
packageNames.add(resolveInfo.activityInfo.packageName);
|
||||
}
|
||||
}
|
||||
LocalRepoService.runProcess(context, packageNames.toArray(new String[0]));
|
||||
|
||||
updater = new IndexUpdater(context, repo);
|
||||
updater.update();
|
||||
assertTrue(updater.hasChanged());
|
||||
assertTrue("repo lastUpdated should be updated", lastUpdated.compareTo(repo.lastUpdated) < 0);
|
||||
|
||||
for (String packageName : packageNames) {
|
||||
assertNotNull(ApkProvider.Helper.findByPackageName(context, packageName));
|
||||
}
|
||||
} finally {
|
||||
if (localHttpd != null) {
|
||||
localHttpd.stop();
|
||||
}
|
||||
}
|
||||
if (localHttpd != null) {
|
||||
assertFalse(localHttpd.isAlive());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isPortInUse(String host, int port) {
|
||||
boolean result = false;
|
||||
|
||||
try {
|
||||
(new Socket(host, port)).close();
|
||||
result = true;
|
||||
} catch (IOException e) {
|
||||
// Could not connect.
|
||||
e.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean isSystemPackage(ResolveInfo resolveInfo) {
|
||||
return (resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
|
||||
}
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
package org.fdroid.fdroid.work;
|
||||
|
||||
import android.app.Instrumentation;
|
||||
import androidx.arch.core.executor.testing.InstantTaskExecutorRule;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.work.OneTimeWorkRequest;
|
||||
import androidx.work.WorkInfo;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.fdroid.fdroid.compat.FileCompatTest;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* This test cannot run on Robolectric unfortunately since it does not support
|
||||
* getting the timestamps from the files completely.
|
||||
* <p>
|
||||
* This is marked with {@link LargeTest} because it always fails on the emulator
|
||||
* tests on GitLab CI. That excludes it from the test run there.
|
||||
*/
|
||||
@LargeTest
|
||||
public class CleanCacheWorkerTest {
|
||||
public static final String TAG = "CleanCacheWorkerEmulatorTest";
|
||||
|
||||
@Rule
|
||||
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
|
||||
|
||||
@Rule
|
||||
public WorkManagerTestRule workManagerTestRule = new WorkManagerTestRule();
|
||||
|
||||
@Test
|
||||
public void testWorkRequest() throws ExecutionException, InterruptedException {
|
||||
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(CleanCacheWorker.class).build();
|
||||
workManagerTestRule.workManager.enqueue(request).getResult();
|
||||
ListenableFuture<WorkInfo> workInfo = workManagerTestRule.workManager.getWorkInfoById(request.getId());
|
||||
assertEquals(WorkInfo.State.SUCCEEDED, workInfo.get().getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClearOldFiles() throws IOException, InterruptedException {
|
||||
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
||||
File tempDir = FileCompatTest.getWriteableDir(instrumentation);
|
||||
assertTrue(tempDir.isDirectory());
|
||||
assertTrue(tempDir.canWrite());
|
||||
|
||||
File dir = new File(tempDir, "F-Droid-test.clearOldFiles");
|
||||
FileUtils.deleteQuietly(dir);
|
||||
assertTrue(dir.mkdirs());
|
||||
assertTrue(dir.isDirectory());
|
||||
|
||||
File first = new File(dir, "first");
|
||||
first.deleteOnExit();
|
||||
|
||||
File second = new File(dir, "second");
|
||||
second.deleteOnExit();
|
||||
|
||||
assertFalse(first.exists());
|
||||
assertFalse(second.exists());
|
||||
|
||||
assertTrue(first.createNewFile());
|
||||
assertTrue(first.exists());
|
||||
|
||||
Thread.sleep(7000);
|
||||
assertTrue(second.createNewFile());
|
||||
assertTrue(second.exists());
|
||||
|
||||
CleanCacheWorker.clearOldFiles(dir, 3000); // check all in dir
|
||||
assertFalse(first.exists());
|
||||
assertTrue(second.exists());
|
||||
|
||||
Thread.sleep(7000);
|
||||
CleanCacheWorker.clearOldFiles(second, 3000); // check just second file
|
||||
assertFalse(first.exists());
|
||||
assertFalse(second.exists());
|
||||
|
||||
// make sure it doesn't freak out on a non-existent file
|
||||
File nonexistent = new File(tempDir, "nonexistent");
|
||||
CleanCacheWorker.clearOldFiles(nonexistent, 1);
|
||||
CleanCacheWorker.clearOldFiles(null, 1);
|
||||
}
|
||||
|
||||
/*
|
||||
// TODO enable this once getImageCacheDir() can be mocked or provide a writable dir in the test
|
||||
@Test
|
||||
public void testDeleteOldIcons() throws IOException {
|
||||
Context context = InstrumentationRegistry.getInstrumentation().getContext();
|
||||
File imageCacheDir = Utils.getImageCacheDir(context);
|
||||
imageCacheDir.mkdirs();
|
||||
assertTrue(imageCacheDir.isDirectory());
|
||||
File oldIcon = new File(imageCacheDir, "old.png");
|
||||
assertTrue(oldIcon.createNewFile());
|
||||
Assume.assumeTrue("test environment must be able to set LastModified time",
|
||||
oldIcon.setLastModified(System.currentTimeMillis() - (DateUtils.DAY_IN_MILLIS * 370)));
|
||||
File currentIcon = new File(imageCacheDir, "current.png");
|
||||
assertTrue(currentIcon.createNewFile());
|
||||
CleanCacheWorker.deleteOldIcons(context);
|
||||
assertTrue(currentIcon.exists());
|
||||
assertFalse(oldIcon.exists());
|
||||
}
|
||||
*/
|
||||
}
|
@ -1,72 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2021 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.work;
|
||||
|
||||
import androidx.arch.core.executor.testing.InstantTaskExecutorRule;
|
||||
import androidx.test.filters.LargeTest;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.work.OneTimeWorkRequest;
|
||||
import androidx.work.WorkInfo;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* This actually runs {@link FDroidMetricsWorker} on a device/emulator and
|
||||
* submits a report to https://metrics.cleaninsights.org
|
||||
* <p>
|
||||
* This is marked with {@link LargeTest} to exclude it from running on GitLab CI
|
||||
* because it always fails on the emulator tests there. Also, it actually submits
|
||||
* a report.
|
||||
*/
|
||||
@LargeTest
|
||||
public class FDroidMetricsWorkerTest {
|
||||
public static final String TAG = "FDroidMetricsWorkerTest";
|
||||
|
||||
@Rule
|
||||
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
|
||||
|
||||
@Rule
|
||||
public WorkManagerTestRule workManagerTestRule = new WorkManagerTestRule();
|
||||
|
||||
/**
|
||||
* A test for easy manual testing.
|
||||
*/
|
||||
@Ignore
|
||||
@Test
|
||||
public void testGenerateReport() throws IOException {
|
||||
String json = FDroidMetricsWorker.generateReport(
|
||||
InstrumentationRegistry.getInstrumentation().getTargetContext());
|
||||
System.out.println(json);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWorkRequest() throws ExecutionException, InterruptedException {
|
||||
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(FDroidMetricsWorker.class).build();
|
||||
workManagerTestRule.workManager.enqueue(request).getResult();
|
||||
ListenableFuture<WorkInfo> workInfo = workManagerTestRule.workManager.getWorkInfoById(request.getId());
|
||||
assertEquals(WorkInfo.State.SUCCEEDED, workInfo.get().getState());
|
||||
}
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
package org.fdroid.fdroid.work;
|
||||
|
||||
import android.app.Instrumentation;
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import androidx.test.platform.app.InstrumentationRegistry;
|
||||
import androidx.work.Configuration;
|
||||
import androidx.work.WorkManager;
|
||||
import androidx.work.testing.SynchronousExecutor;
|
||||
import androidx.work.testing.WorkManagerTestInitHelper;
|
||||
import org.junit.rules.TestWatcher;
|
||||
import org.junit.runner.Description;
|
||||
|
||||
public class WorkManagerTestRule extends TestWatcher {
|
||||
Context targetContext;
|
||||
Context testContext;
|
||||
Configuration configuration;
|
||||
WorkManager workManager;
|
||||
|
||||
@Override
|
||||
protected void starting(Description description) {
|
||||
final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
||||
targetContext = instrumentation.getTargetContext();
|
||||
testContext = instrumentation.getContext();
|
||||
configuration = new Configuration.Builder()
|
||||
.setMinimumLoggingLevel(Log.DEBUG)
|
||||
.setExecutor(new SynchronousExecutor())
|
||||
.build();
|
||||
|
||||
WorkManagerTestInitHelper.initializeTestWorkManager(targetContext, configuration);
|
||||
workManager = WorkManager.getInstance(targetContext);
|
||||
}
|
||||
}
|
9
app/src/androidTest/proguard-rules.pro
vendored
@ -1,7 +1,3 @@
|
||||
-dontoptimize
|
||||
-dontwarn
|
||||
-dontobfuscate
|
||||
|
||||
-dontwarn android.test.**
|
||||
-dontwarn android.support.test.**
|
||||
-dontnote junit.framework.**
|
||||
@ -18,8 +14,3 @@
|
||||
|
||||
-keep class junit.** { *; }
|
||||
-dontwarn junit.**
|
||||
|
||||
# This is necessary so that RemoteWorkManager can be initialized (also marked with @Keep)
|
||||
-keep class androidx.work.multiprocess.RemoteWorkManagerClient {
|
||||
public <init>(...);
|
||||
}
|
||||
|
@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
|
||||
public class BluetoothClient {
|
||||
|
||||
public BluetoothClient(String ignored) {
|
||||
}
|
||||
|
||||
public BluetoothConnection openConnection() {
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
public class LocalRepoManager {
|
||||
public static final String[] WEB_ROOT_ASSET_FILES = {};
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class SDCardScannerService {
|
||||
public static void scan(Context context) {
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class SwapService {
|
||||
public static void start(Context context) {
|
||||
}
|
||||
}
|
@ -1,34 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class SwapWorkflowActivity {
|
||||
|
||||
public static final String EXTRA_PREVENT_FURTHER_SWAP_REQUESTS = "preventFurtherSwap";
|
||||
|
||||
public static void requestSwap(Context context, Uri uri) {
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import android.content.Intent;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class TreeUriScannerIntentService {
|
||||
public static void onActivityResult(AppCompatActivity activity, Intent intent) {
|
||||
throw new IllegalStateException("unimplemented");
|
||||
}
|
||||
}
|
@ -1,35 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class WifiStateChangeService {
|
||||
public static void start(Context context, @Nullable Intent intent) {
|
||||
}
|
||||
|
||||
public class WifiInfoThread extends Thread {
|
||||
}
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby.peers;
|
||||
|
||||
import org.fdroid.fdroid.data.NewRepoConfig;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class WifiPeer {
|
||||
public WifiPeer(NewRepoConfig config) {
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* Dummy version for basic app flavor.
|
||||
*/
|
||||
public class HidingManager {
|
||||
|
||||
public static boolean isHidden(Context context) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void showHideDialog(final Context context) {
|
||||
throw new IllegalStateException("unimplemented");
|
||||
}
|
||||
|
||||
}
|
@ -1,99 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.views.main;
|
||||
|
||||
import android.widget.FrameLayout;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.views.PreferencesFragment;
|
||||
import org.fdroid.fdroid.views.updates.UpdatesViewBinder;
|
||||
|
||||
/**
|
||||
* Decides which view on the main screen to attach to a given {@link FrameLayout}. This class
|
||||
* doesn't know which view it will be rendering at the time it is constructed. Rather, at some
|
||||
* point in the future the {@link MainViewAdapter} will have information about which view we
|
||||
* are required to render, and will invoke the relevant "bind*()" method on this class.
|
||||
*/
|
||||
class MainViewController extends RecyclerView.ViewHolder {
|
||||
|
||||
private final AppCompatActivity activity;
|
||||
private final FrameLayout frame;
|
||||
|
||||
@Nullable
|
||||
private UpdatesViewBinder updatesView = null;
|
||||
|
||||
MainViewController(AppCompatActivity activity, FrameLayout frame) {
|
||||
super(frame);
|
||||
this.activity = activity;
|
||||
this.frame = frame;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see LatestViewBinder
|
||||
*/
|
||||
public void bindLatestView() {
|
||||
new LatestViewBinder(activity, frame);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see UpdatesViewBinder
|
||||
*/
|
||||
public void bindUpdates() {
|
||||
if (updatesView == null) {
|
||||
updatesView = new UpdatesViewBinder(activity, frame);
|
||||
}
|
||||
|
||||
updatesView.bind();
|
||||
}
|
||||
|
||||
public void unbindUpdates() {
|
||||
if (updatesView != null) {
|
||||
updatesView.unbind();
|
||||
}
|
||||
}
|
||||
|
||||
public void bindCategoriesView() {
|
||||
throw new IllegalStateException("unimplemented");
|
||||
}
|
||||
|
||||
public void bindSwapView() {
|
||||
throw new IllegalStateException("unimplemented");
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches a {@link PreferencesFragment} to the view. Everything else is managed by the
|
||||
* fragment itself, so no further work needs to be done by this view binder.
|
||||
* <p>
|
||||
* Note: It is tricky to attach a {@link Fragment} to a view from this view holder. This is due
|
||||
* to the way in which the {@link RecyclerView} will reuse existing views and ask us to
|
||||
* put a settings fragment in there at arbitrary times. Usually it wont be the same view we
|
||||
* attached the fragment to last time, which causes weirdness. The solution is to use code from
|
||||
* the com.lsjwzh.widget.recyclerviewpager.FragmentStatePagerAdapter which manages this.
|
||||
* The code has been ported to {@link SettingsView}.
|
||||
*
|
||||
* @see SettingsView
|
||||
*/
|
||||
public void bindSettingsView() {
|
||||
activity.getLayoutInflater().inflate(R.layout.main_tab_settings, frame, true);
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
package org.fdroid.fdroid.views.main;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
class NearbyViewBinder {
|
||||
public static void updateUsbOtg(Context context) {
|
||||
throw new IllegalStateException("unimplemented");
|
||||
}
|
||||
}
|
Before Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 5.5 KiB |
Before Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 40 KiB |
Before Width: | Height: | Size: 65 KiB |
@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<menu xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
tools:ignore="MenuTitle">
|
||||
<!-- android:title and android:icon are set dynamically in MainActivity -->
|
||||
<item
|
||||
app:showAsAction="ifRoom|withText"
|
||||
android:id="@+id/latest"/>
|
||||
<item
|
||||
app:showAsAction="ifRoom|withText"
|
||||
android:id="@+id/updates"/>
|
||||
<item
|
||||
app:showAsAction="ifRoom|withText"
|
||||
android:id="@+id/settings"/>
|
||||
</menu>
|
@ -1,5 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">F-Droid Basic</string>
|
||||
<string name="about_title">About F-Droid Basic</string>
|
||||
</resources>
|
@ -1,183 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<PreferenceScreen android:title="@string/about_title"
|
||||
android:key="pref_about" />
|
||||
|
||||
<PreferenceCategory android:title="@string/preference_category__my_apps">
|
||||
<PreferenceScreen android:title="@string/preference_manage_installed_apps">
|
||||
<intent
|
||||
android:action="android.intent.action.MAIN"
|
||||
android:targetPackage="@string/applicationId"
|
||||
android:targetClass="org.fdroid.fdroid.views.installed.InstalledAppsActivity"/>
|
||||
</PreferenceScreen>
|
||||
<PreferenceScreen
|
||||
android:title="@string/menu_manage"
|
||||
android:summary="@string/repositories_summary">
|
||||
<intent
|
||||
android:action="android.intent.action.MAIN"
|
||||
android:targetPackage="@string/applicationId"
|
||||
android:targetClass="org.fdroid.fdroid.views.ManageReposActivity"/>
|
||||
</PreferenceScreen>
|
||||
<PreferenceScreen
|
||||
android:key="installHistory"
|
||||
android:visible="false"
|
||||
android:title="@string/install_history"
|
||||
android:summary="@string/install_history_summary">
|
||||
<intent
|
||||
android:action="android.intent.action.MAIN"
|
||||
android:targetPackage="@string/applicationId"
|
||||
android:targetClass="org.fdroid.fdroid.views.InstallHistoryActivity"/>
|
||||
</PreferenceScreen>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory android:title="@string/updates">
|
||||
<org.fdroid.fdroid.views.LiveSeekBarPreference
|
||||
android:key="overWifi"
|
||||
android:title="@string/over_wifi"
|
||||
android:defaultValue="@integer/defaultOverWifi"
|
||||
android:layout="@layout/preference_seekbar"/>
|
||||
<org.fdroid.fdroid.views.LiveSeekBarPreference
|
||||
android:key="overData"
|
||||
android:title="@string/over_data"
|
||||
android:defaultValue="@integer/defaultOverData"
|
||||
android:layout="@layout/preference_seekbar"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/update_auto_download"
|
||||
android:summary="@string/update_auto_download_summary"
|
||||
android:key="updateAutoDownload"/>
|
||||
<org.fdroid.fdroid.views.LiveSeekBarPreference
|
||||
android:key="updateIntervalSeekBarPosition"
|
||||
android:title="@string/update_interval"
|
||||
android:defaultValue="@integer/defaultUpdateInterval"
|
||||
android:layout="@layout/preference_seekbar"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/notify"
|
||||
android:defaultValue="true"
|
||||
android:key="updateNotify"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory android:title="@string/display"
|
||||
android:key="pref_category_display">
|
||||
<ListPreference
|
||||
android:title="@string/pref_language"
|
||||
android:key="language"/>
|
||||
<ListPreference
|
||||
android:title="@string/theme"
|
||||
android:key="theme"
|
||||
android:defaultValue="light"
|
||||
android:entries="@array/themeNames"
|
||||
android:entryValues="@array/themeValues"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory android:title="@string/appcompatibility"
|
||||
android:key="pref_category_appcompatibility">
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/show_incompat_versions"
|
||||
android:defaultValue="false"
|
||||
android:key="incompatibleVersions"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/show_anti_feature_apps"
|
||||
android:defaultValue="false"
|
||||
android:key="showAntiFeatureApps"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/force_touch_apps"
|
||||
android:defaultValue="false"
|
||||
android:key="ignoreTouchscreen"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory android:title="@string/proxy">
|
||||
<SwitchPreferenceCompat
|
||||
android:key="useTor"
|
||||
android:summary="@string/useTorSummary"
|
||||
android:title="@string/useTor"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:defaultValue="false"
|
||||
android:key="enableProxy"
|
||||
android:title="@string/enable_proxy_title"
|
||||
android:summary="@string/enable_proxy_summary"/>
|
||||
<EditTextPreference
|
||||
android:key="proxyHost"
|
||||
android:title="@string/proxy_host"
|
||||
android:summary="@string/proxy_host_summary"
|
||||
android:dependency="enableProxy"/>
|
||||
<EditTextPreference
|
||||
android:key="proxyPort"
|
||||
android:title="@string/proxy_port"
|
||||
android:summary="@string/proxy_port_summary"
|
||||
android:dependency="enableProxy"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory
|
||||
android:key="pref_category_privacy"
|
||||
android:title="@string/privacy">
|
||||
<SwitchPreferenceCompat
|
||||
android:key="promptToSendCrashReports"
|
||||
android:title="@string/prompt_to_send_crash_reports"
|
||||
android:summary="@string/prompt_to_send_crash_reports_summary"
|
||||
android:defaultValue="true"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:defaultValue="false"
|
||||
android:key="preventScreenshots"
|
||||
android:summary="@string/preventScreenshots_summary"
|
||||
android:title="@string/preventScreenshots_title"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
<PreferenceCategory
|
||||
android:title="@string/other"
|
||||
android:key="pref_category_other">
|
||||
<ListPreference
|
||||
android:title="@string/cache_downloaded"
|
||||
android:key="keepCacheFor"
|
||||
android:defaultValue="86400000"
|
||||
android:entries="@array/keepCacheNames"
|
||||
android:entryValues="@array/keepCacheValues"/>
|
||||
<SwitchPreferenceCompat
|
||||
android:title="@string/expert"
|
||||
android:defaultValue="false"
|
||||
android:key="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="unstableUpdates"
|
||||
android:title="@string/unstable_updates"
|
||||
android:summary="@string/unstable_updates_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="keepInstallHistory"
|
||||
android:title="@string/keep_install_history"
|
||||
android:summary="@string/keep_install_history_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="sendToFdroidMetrics"
|
||||
android:title="@string/send_to_fdroid_metrics"
|
||||
android:summary="@string/send_to_fdroid_metrics_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="hideAllNotifications"
|
||||
android:title="@string/hide_all_notifications"
|
||||
android:summary="@string/hide_all_notifications_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="sendVersionAndUUIDToServers"
|
||||
android:title="@string/send_version_and_uuid"
|
||||
android:summary="@string/send_version_and_uuid_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:key="forceOldIndex"
|
||||
android:title="@string/force_old_index"
|
||||
android:summary="@string/force_old_index_summary"
|
||||
android:defaultValue="false"
|
||||
android:dependency="expert"/>
|
||||
<CheckBoxPreference
|
||||
android:title="@string/system_installer"
|
||||
android:defaultValue="false"
|
||||
android:key="privilegedInstaller"
|
||||
android:persistent="false"
|
||||
android:dependency="expert"/>
|
||||
</PreferenceCategory>
|
||||
|
||||
</PreferenceScreen>
|
@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- This file should be outside of release manifest (in this case app/src/mock/Manifest.xml -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<!--required to enable/disable system animations from the app itself during Espresso test runs-->
|
||||
<uses-permission android:name="android.permission.SET_ANIMATION_SCALE" />
|
||||
</manifest>
|
@ -1,179 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
* Copyright (C) 2010-2012 Ciaran Gultnieks
|
||||
* Copyright (C) 2013-2017 Peter Serwylo
|
||||
* Copyright (C) 2014-2015 Daniel Martí
|
||||
* Copyright (C) 2014-2018 Hans-Christoph Steiner
|
||||
* Copyright (C) 2016 Dominik Schürmann
|
||||
* Copyright (C) 2018 Torsten Grote
|
||||
* Copyright (C) 2018 Senecto Limited
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
-->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="org.fdroid.fdroid"
|
||||
android:installLocation="auto">
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.nfc"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.bluetooth"
|
||||
android:required="false" />
|
||||
|
||||
<uses-feature
|
||||
android:name="android.hardware.usb.host"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.NFC" />
|
||||
<uses-permission
|
||||
android:name="android.permission.USB_PERMISSION"
|
||||
android:maxSdkVersion="22" /><!-- maybe unnecessary -->
|
||||
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
|
||||
<application>
|
||||
|
||||
<activity
|
||||
android:name=".nearby.SwapWorkflowActivity"
|
||||
android:configChanges="orientation|keyboardHidden"
|
||||
android:label="@string/swap"
|
||||
android:launchMode="singleTask"
|
||||
android:parentActivityName=".views.main.MainActivity"
|
||||
android:screenOrientation="portrait">
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value=".views.main.MainActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".panic.PanicPreferencesActivity"
|
||||
android:label="@string/panic_settings"
|
||||
android:parentActivityName=".views.main.MainActivity">
|
||||
<intent-filter>
|
||||
<action android:name="info.guardianproject.panic.action.CONNECT" />
|
||||
<action android:name="info.guardianproject.panic.action.DISCONNECT" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
|
||||
<meta-data
|
||||
android:name="android.support.PARENT_ACTIVITY"
|
||||
android:value=".views.main.MainActivity" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".panic.SelectInstalledAppsActivity"
|
||||
android:parentActivityName=".panic.PanicPreferencesActivity" />
|
||||
|
||||
<activity
|
||||
android:name=".panic.PanicResponderActivity"
|
||||
android:noHistory="true"
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
|
||||
<!-- this can never have launchMode singleTask or singleInstance! -->
|
||||
<intent-filter>
|
||||
<action android:name="info.guardianproject.panic.action.TRIGGER" />
|
||||
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity
|
||||
android:name=".panic.ExitActivity"
|
||||
android:theme="@android:style/Theme.NoDisplay" />
|
||||
|
||||
<activity
|
||||
android:name=".panic.CalculatorActivity"
|
||||
android:enabled="false"
|
||||
android:icon="@mipmap/ic_calculator_launcher"
|
||||
android:label="@string/hiding_calculator">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<receiver android:name=".nearby.WifiStateChangeReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.net.wifi.STATE_CHANGE" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver android:name=".receiver.DeviceStorageReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.DEVICE_STORAGE_LOW" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver android:name=".nearby.UsbDeviceAttachedReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
|
||||
android:resource="@xml/device_filter" />
|
||||
</receiver>
|
||||
<receiver android:name=".nearby.UsbDeviceDetachedReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"
|
||||
android:resource="@xml/device_filter" />
|
||||
</receiver>
|
||||
<receiver android:name=".nearby.UsbDeviceMediaMountedReceiver">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MEDIA_EJECT" />
|
||||
<action android:name="android.intent.action.MEDIA_REMOVED" />
|
||||
<action android:name="android.intent.action.MEDIA_MOUNTED" />
|
||||
<action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
|
||||
|
||||
<data android:scheme="content" />
|
||||
<data android:scheme="file" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<service
|
||||
android:name=".nearby.WifiStateChangeService"
|
||||
android:exported="false" />
|
||||
<service android:name=".nearby.SwapService" />
|
||||
|
||||
<service
|
||||
android:name=".nearby.LocalRepoService"
|
||||
android:exported="false" />
|
||||
<service
|
||||
android:name=".nearby.TreeUriScannerIntentService"
|
||||
android:exported="false" />
|
||||
<service
|
||||
android:name=".nearby.SDCardScannerService"
|
||||
android:exported="false" />
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
@ -1,94 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2010 Ken Ellinwood.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package kellinwood.logging;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
public abstract class AbstractLogger implements LoggerInterface {
|
||||
|
||||
protected String category;
|
||||
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
|
||||
|
||||
public AbstractLogger(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
protected String format(String level, String message) {
|
||||
return String.format("%s %s %s: %s\n", dateFormat.format(new Date()), level, category, message);
|
||||
}
|
||||
|
||||
protected abstract void write(String level, String message, Throwable t);
|
||||
|
||||
protected void writeFixNullMessage(String level, String message, Throwable t) {
|
||||
if (message == null) {
|
||||
if (t != null) message = t.getClass().getName();
|
||||
else message = "null";
|
||||
}
|
||||
write(level, message, t);
|
||||
}
|
||||
|
||||
public void debug(String message, Throwable t) {
|
||||
writeFixNullMessage(DEBUG, message, t);
|
||||
}
|
||||
|
||||
public void debug(String message) {
|
||||
writeFixNullMessage(DEBUG, message, null);
|
||||
}
|
||||
|
||||
public void error(String message, Throwable t) {
|
||||
writeFixNullMessage(ERROR, message, t);
|
||||
}
|
||||
|
||||
public void error(String message) {
|
||||
writeFixNullMessage(ERROR, message, null);
|
||||
}
|
||||
|
||||
public void info(String message, Throwable t) {
|
||||
writeFixNullMessage(INFO, message, t);
|
||||
}
|
||||
|
||||
public void info(String message) {
|
||||
writeFixNullMessage(INFO, message, null);
|
||||
}
|
||||
|
||||
public void warning(String message, Throwable t) {
|
||||
writeFixNullMessage(WARNING, message, t);
|
||||
}
|
||||
|
||||
public void warning(String message) {
|
||||
writeFixNullMessage(WARNING, message, null);
|
||||
}
|
||||
|
||||
public boolean isDebugEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isErrorEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isInfoEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isWarningEnabled() {
|
||||
return true;
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2010 Ken Ellinwood.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package kellinwood.logging;
|
||||
|
||||
public interface LoggerInterface {
|
||||
|
||||
public static final String ERROR = "ERROR";
|
||||
public static final String WARNING = "WARNING";
|
||||
public static final String INFO = "INFO";
|
||||
public static final String DEBUG = "DEBUG";
|
||||
|
||||
public boolean isErrorEnabled();
|
||||
|
||||
public void error(String message);
|
||||
|
||||
public void error(String message, Throwable t);
|
||||
|
||||
|
||||
public boolean isWarningEnabled();
|
||||
|
||||
public void warning(String message);
|
||||
|
||||
public void warning(String message, Throwable t);
|
||||
|
||||
public boolean isInfoEnabled();
|
||||
|
||||
public void info(String message);
|
||||
|
||||
public void info(String message, Throwable t);
|
||||
|
||||
public boolean isDebugEnabled();
|
||||
|
||||
public void debug(String message);
|
||||
|
||||
public void debug(String message, Throwable t);
|
||||
|
||||
|
||||
}
|
@ -1,70 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2010 Ken Ellinwood.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package kellinwood.logging;
|
||||
|
||||
public class NullLoggerFactory implements LoggerFactory {
|
||||
|
||||
static LoggerInterface logger = new LoggerInterface() {
|
||||
|
||||
public void debug(String message) {
|
||||
}
|
||||
|
||||
public void debug(String message, Throwable t) {
|
||||
}
|
||||
|
||||
public void error(String message) {
|
||||
}
|
||||
|
||||
public void error(String message, Throwable t) {
|
||||
}
|
||||
|
||||
public void info(String message) {
|
||||
}
|
||||
|
||||
public void info(String message, Throwable t) {
|
||||
}
|
||||
|
||||
public boolean isDebugEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isErrorEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isInfoEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isWarningEnabled() {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void warning(String message) {
|
||||
}
|
||||
|
||||
public void warning(String message, Throwable t) {
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
public LoggerInterface getLogger(String category) {
|
||||
return logger;
|
||||
}
|
||||
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
|
||||
package kellinwood.security.zipsigner.optional;
|
||||
|
||||
import kellinwood.security.zipsigner.ZipSigner;
|
||||
|
||||
import java.security.Key;
|
||||
import java.security.KeyStore;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
/**
|
||||
*/
|
||||
public class CustomKeySigner {
|
||||
|
||||
/**
|
||||
* KeyStore-type agnostic. This method will sign the zip file, automatically handling JKS or BKS keystores.
|
||||
*/
|
||||
public static void signZip(ZipSigner zipSigner,
|
||||
String keystorePath,
|
||||
char[] keystorePw,
|
||||
String certAlias,
|
||||
char[] certPw,
|
||||
String signatureAlgorithm,
|
||||
String inputZipFilename,
|
||||
String outputZipFilename)
|
||||
throws Exception {
|
||||
zipSigner.issueLoadingCertAndKeysProgressEvent();
|
||||
KeyStore keystore = KeyStoreFileManager.loadKeyStore(keystorePath, keystorePw);
|
||||
Certificate cert = keystore.getCertificate(certAlias);
|
||||
X509Certificate publicKey = (X509Certificate) cert;
|
||||
Key key = keystore.getKey(certAlias, certPw);
|
||||
PrivateKey privateKey = (PrivateKey) key;
|
||||
|
||||
zipSigner.setKeys("custom", publicKey, privateKey, signatureAlgorithm, null);
|
||||
zipSigner.signZip(inputZipFilename, outputZipFilename);
|
||||
}
|
||||
|
||||
}
|
@ -1,89 +0,0 @@
|
||||
|
||||
package kellinwood.security.zipsigner.optional;
|
||||
|
||||
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
|
||||
import org.bouncycastle.asn1.x500.style.BCStyle;
|
||||
import org.bouncycastle.jce.X509Principal;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Vector;
|
||||
|
||||
|
||||
/**
|
||||
* Helper class for dealing with the distinguished name RDNs.
|
||||
*/
|
||||
public class DistinguishedNameValues extends LinkedHashMap<ASN1ObjectIdentifier, String> {
|
||||
|
||||
public DistinguishedNameValues() {
|
||||
put(BCStyle.C, null);
|
||||
put(BCStyle.ST, null);
|
||||
put(BCStyle.L, null);
|
||||
put(BCStyle.STREET, null);
|
||||
put(BCStyle.O, null);
|
||||
put(BCStyle.OU, null);
|
||||
put(BCStyle.CN, null);
|
||||
}
|
||||
|
||||
public String put(ASN1ObjectIdentifier oid, String value) {
|
||||
if (value != null && value.equals("")) value = null;
|
||||
if (containsKey(oid)) super.put(oid, value); // preserve original ordering
|
||||
else {
|
||||
super.put(oid, value);
|
||||
// String cn = remove(BCStyle.CN); // CN will always be last.
|
||||
// put(BCStyle.CN,cn);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
put(BCStyle.C, country);
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
put(BCStyle.ST, state);
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
put(BCStyle.L, locality);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
put(BCStyle.STREET, street);
|
||||
}
|
||||
|
||||
public void setOrganization(String organization) {
|
||||
put(BCStyle.O, organization);
|
||||
}
|
||||
|
||||
public void setOrganizationalUnit(String organizationalUnit) {
|
||||
put(BCStyle.OU, organizationalUnit);
|
||||
}
|
||||
|
||||
public void setCommonName(String commonName) {
|
||||
put(BCStyle.CN, commonName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
int result = 0;
|
||||
for (String value : values()) {
|
||||
if (value != null) result += 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public X509Principal getPrincipal() {
|
||||
Vector<ASN1ObjectIdentifier> oids = new Vector<ASN1ObjectIdentifier>();
|
||||
Vector<String> values = new Vector<String>();
|
||||
|
||||
for (Map.Entry<ASN1ObjectIdentifier, String> entry : entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().equals("")) {
|
||||
oids.add(entry.getKey());
|
||||
values.add(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
return new X509Principal(oids, values);
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.bluetooth.BluetoothSocket;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class BluetoothClient {
|
||||
private static final String TAG = "BluetoothClient";
|
||||
|
||||
private final BluetoothDevice device;
|
||||
|
||||
public BluetoothClient(String macAddress) {
|
||||
device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress);
|
||||
}
|
||||
|
||||
public BluetoothConnection openConnection() throws IOException {
|
||||
|
||||
BluetoothConnection connection = null;
|
||||
try {
|
||||
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(BluetoothConstants.fdroidUuid());
|
||||
connection = new BluetoothConnection(socket);
|
||||
connection.open();
|
||||
return connection;
|
||||
} finally {
|
||||
if (connection != null) {
|
||||
connection.closeQuietly();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,179 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.nearby.peers.BluetoothPeer;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
|
||||
/**
|
||||
* Manage the {@link android.bluetooth.BluetoothAdapter}in a {@link HandlerThread}.
|
||||
* The start process is in {@link HandlerThread#onLooperPrepared()} so that it is
|
||||
* always started before any messages get delivered from the queue.
|
||||
*
|
||||
* @see BonjourManager
|
||||
* @see LocalRepoManager
|
||||
*/
|
||||
public class BluetoothManager {
|
||||
private static final String TAG = "BluetoothManager";
|
||||
|
||||
public static final String ACTION_FOUND = "BluetoothNewPeer";
|
||||
public static final String EXTRA_PEER = "extraBluetoothPeer";
|
||||
|
||||
public static final String ACTION_STATUS = "BluetoothStatus";
|
||||
public static final String EXTRA_STATUS = "BluetoothStatusExtra";
|
||||
public static final int STATUS_STARTING = 0;
|
||||
public static final int STATUS_STARTED = 1;
|
||||
public static final int STATUS_STOPPING = 2;
|
||||
public static final int STATUS_STOPPED = 3;
|
||||
public static final int STATUS_ERROR = 0xffff;
|
||||
|
||||
private static final int STOP = 5709;
|
||||
|
||||
private static WeakReference<Context> context;
|
||||
private static Handler handler;
|
||||
private static volatile HandlerThread handlerThread;
|
||||
private static BluetoothAdapter bluetoothAdapter;
|
||||
|
||||
/**
|
||||
* Stops the Bluetooth adapter, triggering a status broadcast via {@link #ACTION_STATUS}.
|
||||
* {@link #STATUS_STOPPED} can be broadcast multiple times for the same session,
|
||||
* so make sure {@link android.content.BroadcastReceiver}s handle duplicates.
|
||||
*/
|
||||
public static void stop(Context context) {
|
||||
BluetoothManager.context = new WeakReference<>(context);
|
||||
if (handler == null || handlerThread == null || !handlerThread.isAlive()) {
|
||||
Log.w(TAG, "handlerThread is already stopped, doing nothing!");
|
||||
sendBroadcast(STATUS_STOPPED, null);
|
||||
return;
|
||||
}
|
||||
sendBroadcast(STATUS_STOPPING, null);
|
||||
handler.sendEmptyMessage(STOP);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the service, triggering a status broadcast via {@link #ACTION_STATUS}.
|
||||
* {@link #STATUS_STARTED} can be broadcast multiple times for the same session,
|
||||
* so make sure {@link android.content.BroadcastReceiver}s handle duplicates.
|
||||
*/
|
||||
public static void start(final Context context) {
|
||||
BluetoothManager.context = new WeakReference<>(context);
|
||||
if (handlerThread != null && handlerThread.isAlive()) {
|
||||
sendBroadcast(STATUS_STARTED, null);
|
||||
return;
|
||||
}
|
||||
sendBroadcast(STATUS_STARTING, null);
|
||||
|
||||
final BluetoothServer bluetoothServer = new BluetoothServer(context.getFilesDir());
|
||||
handlerThread = new HandlerThread("BluetoothManager", Process.THREAD_PRIORITY_LESS_FAVORABLE) {
|
||||
@Override
|
||||
protected void onLooperPrepared() {
|
||||
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
|
||||
localBroadcastManager.registerReceiver(bluetoothDeviceFound,
|
||||
new IntentFilter(BluetoothDevice.ACTION_FOUND));
|
||||
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
String name = bluetoothAdapter.getName();
|
||||
if (name != null) {
|
||||
SwapService.putBluetoothNameBeforeSwap(name);
|
||||
}
|
||||
if (!bluetoothAdapter.enable()) {
|
||||
sendBroadcast(STATUS_ERROR, context.getString(R.string.swap_error_cannot_start_bluetooth));
|
||||
return;
|
||||
}
|
||||
bluetoothServer.start();
|
||||
if (bluetoothAdapter.startDiscovery()) {
|
||||
sendBroadcast(STATUS_STARTED, null);
|
||||
} else {
|
||||
sendBroadcast(STATUS_ERROR, context.getString(R.string.swap_error_cannot_start_bluetooth));
|
||||
}
|
||||
for (BluetoothDevice device : bluetoothAdapter.getBondedDevices()) {
|
||||
sendFoundBroadcast(context, device);
|
||||
}
|
||||
}
|
||||
};
|
||||
handlerThread.start();
|
||||
handler = new Handler(handlerThread.getLooper()) {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
|
||||
localBroadcastManager.unregisterReceiver(bluetoothDeviceFound);
|
||||
bluetoothServer.close();
|
||||
if (bluetoothAdapter != null) {
|
||||
bluetoothAdapter.cancelDiscovery();
|
||||
if (!SwapService.wasBluetoothEnabledBeforeSwap()) {
|
||||
bluetoothAdapter.disable();
|
||||
}
|
||||
String name = SwapService.getBluetoothNameBeforeSwap();
|
||||
if (name != null) {
|
||||
bluetoothAdapter.setName(name);
|
||||
}
|
||||
}
|
||||
handlerThread.quit();
|
||||
handlerThread = null;
|
||||
sendBroadcast(STATUS_STOPPED, null);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static void restart(Context context) {
|
||||
stop(context);
|
||||
try {
|
||||
handlerThread.join(10000);
|
||||
} catch (InterruptedException | NullPointerException e) {
|
||||
// ignored
|
||||
}
|
||||
start(context);
|
||||
}
|
||||
|
||||
public static void setName(Context context, String name) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
public static boolean isAlive() {
|
||||
return handlerThread != null && handlerThread.isAlive();
|
||||
}
|
||||
|
||||
private static void sendBroadcast(int status, String message) {
|
||||
|
||||
Intent intent = new Intent(ACTION_STATUS);
|
||||
intent.putExtra(EXTRA_STATUS, status);
|
||||
if (!TextUtils.isEmpty(message)) {
|
||||
intent.putExtra(Intent.EXTRA_TEXT, message);
|
||||
}
|
||||
LocalBroadcastManager.getInstance(context.get()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
private static final BroadcastReceiver bluetoothDeviceFound = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
sendFoundBroadcast(context, (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
|
||||
}
|
||||
};
|
||||
|
||||
private static void sendFoundBroadcast(Context context, BluetoothDevice device) {
|
||||
BluetoothPeer bluetoothPeer = BluetoothPeer.getInstance(device);
|
||||
if (bluetoothPeer == null) {
|
||||
Utils.debugLog(TAG, "IGNORING: " + device);
|
||||
return;
|
||||
}
|
||||
Intent intent = new Intent(ACTION_FOUND);
|
||||
intent.putExtra(EXTRA_PEER, bluetoothPeer);
|
||||
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
|
||||
}
|
||||
}
|
@ -1,287 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.nearby.peers.BonjourPeer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashMap;
|
||||
|
||||
import javax.jmdns.JmDNS;
|
||||
import javax.jmdns.ServiceEvent;
|
||||
import javax.jmdns.ServiceInfo;
|
||||
import javax.jmdns.ServiceListener;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
|
||||
/**
|
||||
* Manage {@link JmDNS} in a {@link HandlerThread}. The start process is in
|
||||
* {@link HandlerThread#onLooperPrepared()} so that it is always started before
|
||||
* any messages get delivered from the queue.
|
||||
*/
|
||||
public class BonjourManager {
|
||||
private static final String TAG = "BonjourManager";
|
||||
|
||||
public static final String ACTION_FOUND = "BonjourNewPeer";
|
||||
public static final String ACTION_REMOVED = "BonjourPeerRemoved";
|
||||
public static final String EXTRA_BONJOUR_PEER = "extraBonjourPeer";
|
||||
|
||||
public static final String ACTION_STATUS = "BonjourStatus";
|
||||
public static final String EXTRA_STATUS = "BonjourStatusExtra";
|
||||
public static final int STATUS_STARTING = 0;
|
||||
public static final int STATUS_STARTED = 1;
|
||||
public static final int STATUS_STOPPING = 2;
|
||||
public static final int STATUS_STOPPED = 3;
|
||||
public static final int STATUS_VISIBLE = 4;
|
||||
public static final int STATUS_NOT_VISIBLE = 5;
|
||||
public static final int STATUS_ERROR = 0xffff;
|
||||
|
||||
public static final String HTTP_SERVICE_TYPE = "_http._tcp.local.";
|
||||
public static final String HTTPS_SERVICE_TYPE = "_https._tcp.local.";
|
||||
|
||||
private static final int STOP = 5709;
|
||||
private static final int VISIBLE = 4151873;
|
||||
private static final int NOT_VISIBLE = 144151873;
|
||||
|
||||
private static WeakReference<Context> context;
|
||||
private static Handler handler;
|
||||
private static volatile HandlerThread handlerThread;
|
||||
private static ServiceInfo pairService;
|
||||
private static JmDNS jmdns;
|
||||
private static WifiManager.MulticastLock multicastLock;
|
||||
|
||||
public static boolean isAlive() {
|
||||
return handlerThread != null && handlerThread.isAlive();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the Bonjour/mDNS, triggering a status broadcast via {@link #ACTION_STATUS}.
|
||||
* {@link #STATUS_STOPPED} can be broadcast multiple times for the same session,
|
||||
* so make sure {@link android.content.BroadcastReceiver}s handle duplicates.
|
||||
*/
|
||||
public static void stop(Context context) {
|
||||
BonjourManager.context = new WeakReference<>(context);
|
||||
if (handler == null || handlerThread == null || !handlerThread.isAlive()) {
|
||||
sendBroadcast(STATUS_STOPPED, null);
|
||||
return;
|
||||
}
|
||||
sendBroadcast(STATUS_STOPPING, null);
|
||||
handler.sendEmptyMessage(STOP);
|
||||
}
|
||||
|
||||
public static void setVisible(Context context, boolean visible) {
|
||||
BonjourManager.context = new WeakReference<>(context);
|
||||
if (handler == null || handlerThread == null || !handlerThread.isAlive()) {
|
||||
Log.e(TAG, "handlerThread is stopped, not changing visibility!");
|
||||
return;
|
||||
}
|
||||
if (visible) {
|
||||
handler.sendEmptyMessage(VISIBLE);
|
||||
} else {
|
||||
handler.sendEmptyMessage(NOT_VISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the service, triggering a status broadcast via {@link #ACTION_STATUS}.
|
||||
* {@link #STATUS_STARTED} can be broadcast multiple times for the same session,
|
||||
* so make sure {@link android.content.BroadcastReceiver}s handle duplicates.
|
||||
*/
|
||||
public static void start(Context context) {
|
||||
start(context,
|
||||
Preferences.get().getLocalRepoName(),
|
||||
Preferences.get().isLocalRepoHttpsEnabled(),
|
||||
httpServiceListener, httpsServiceListener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Testable version, not for regular use.
|
||||
*
|
||||
* @see #start(Context)
|
||||
*/
|
||||
static void start(final Context context,
|
||||
final String localRepoName, final boolean useHttps,
|
||||
final ServiceListener httpServiceListener, final ServiceListener httpsServiceListener) {
|
||||
BonjourManager.context = new WeakReference<>(context);
|
||||
if (handlerThread != null && handlerThread.isAlive()) {
|
||||
sendBroadcast(STATUS_STARTED, null);
|
||||
return;
|
||||
}
|
||||
sendBroadcast(STATUS_STARTING, null);
|
||||
|
||||
final WifiManager wifiManager = ContextCompat.getSystemService(context, WifiManager.class);
|
||||
handlerThread = new HandlerThread("BonjourManager", Process.THREAD_PRIORITY_LESS_FAVORABLE) {
|
||||
@Override
|
||||
protected void onLooperPrepared() {
|
||||
try {
|
||||
InetAddress address = InetAddress.getByName(FDroidApp.ipAddressString);
|
||||
jmdns = JmDNS.create(address);
|
||||
jmdns.addServiceListener(HTTP_SERVICE_TYPE, httpServiceListener);
|
||||
jmdns.addServiceListener(HTTPS_SERVICE_TYPE, httpsServiceListener);
|
||||
|
||||
multicastLock = wifiManager.createMulticastLock(context.getPackageName());
|
||||
multicastLock.setReferenceCounted(false);
|
||||
multicastLock.acquire();
|
||||
|
||||
sendBroadcast(STATUS_STARTED, null);
|
||||
} catch (IOException e) {
|
||||
if (handler != null) {
|
||||
handler.removeMessages(VISIBLE);
|
||||
handler.sendMessageAtFrontOfQueue(handler.obtainMessage(STOP));
|
||||
}
|
||||
Log.e(TAG, "Error while registering jmdns service", e);
|
||||
sendBroadcast(STATUS_ERROR, e.getLocalizedMessage());
|
||||
}
|
||||
}
|
||||
};
|
||||
handlerThread.start();
|
||||
handler = new Handler(handlerThread.getLooper()) {
|
||||
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
switch (msg.what) {
|
||||
case VISIBLE:
|
||||
handleVisible(localRepoName, useHttps);
|
||||
break;
|
||||
case NOT_VISIBLE:
|
||||
handleNotVisible();
|
||||
break;
|
||||
case STOP:
|
||||
handleStop();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleVisible(String localRepoName, boolean useHttps) {
|
||||
HashMap<String, String> values = new HashMap<>();
|
||||
values.put(BonjourPeer.PATH, "/fdroid/repo");
|
||||
values.put(BonjourPeer.NAME, localRepoName);
|
||||
values.put(BonjourPeer.FINGERPRINT, FDroidApp.repo.fingerprint);
|
||||
String type;
|
||||
if (useHttps) {
|
||||
values.put(BonjourPeer.TYPE, "fdroidrepos");
|
||||
type = HTTPS_SERVICE_TYPE;
|
||||
} else {
|
||||
values.put(BonjourPeer.TYPE, "fdroidrepo");
|
||||
type = HTTP_SERVICE_TYPE;
|
||||
}
|
||||
ServiceInfo newPairService = ServiceInfo.create(type, localRepoName, FDroidApp.port, 0, 0, values);
|
||||
if (!newPairService.equals(pairService)) try {
|
||||
if (pairService != null) {
|
||||
jmdns.unregisterService(pairService);
|
||||
}
|
||||
jmdns.registerService(newPairService);
|
||||
pairService = newPairService;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
sendBroadcast(STATUS_ERROR, e.getLocalizedMessage());
|
||||
return;
|
||||
}
|
||||
sendBroadcast(STATUS_VISIBLE, null);
|
||||
}
|
||||
|
||||
private void handleNotVisible() {
|
||||
if (pairService != null) {
|
||||
jmdns.unregisterService(pairService);
|
||||
pairService = null;
|
||||
}
|
||||
sendBroadcast(STATUS_NOT_VISIBLE, null);
|
||||
}
|
||||
|
||||
private void handleStop() {
|
||||
if (multicastLock != null) {
|
||||
multicastLock.release();
|
||||
}
|
||||
if (jmdns != null) {
|
||||
jmdns.unregisterAllServices();
|
||||
Utils.closeQuietly(jmdns);
|
||||
pairService = null;
|
||||
jmdns = null;
|
||||
}
|
||||
handlerThread.quit();
|
||||
handlerThread = null;
|
||||
sendBroadcast(STATUS_STOPPED, null);
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
public static void restart(Context context) {
|
||||
restart(context,
|
||||
Preferences.get().getLocalRepoName(),
|
||||
Preferences.get().isLocalRepoHttpsEnabled(),
|
||||
httpServiceListener, httpsServiceListener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Testable version, not for regular use.
|
||||
*
|
||||
* @see #restart(Context)
|
||||
*/
|
||||
static void restart(final Context context,
|
||||
final String localRepoName, final boolean useHttps,
|
||||
final ServiceListener httpServiceListener, final ServiceListener httpsServiceListener) {
|
||||
stop(context);
|
||||
try {
|
||||
handlerThread.join(10000);
|
||||
} catch (InterruptedException | NullPointerException e) {
|
||||
// ignored
|
||||
}
|
||||
start(context, localRepoName, useHttps, httpServiceListener, httpsServiceListener);
|
||||
}
|
||||
|
||||
private static void sendBroadcast(String action, ServiceInfo serviceInfo) {
|
||||
BonjourPeer bonjourPeer = BonjourPeer.getInstance(serviceInfo);
|
||||
if (bonjourPeer == null) {
|
||||
Utils.debugLog(TAG, "IGNORING: " + serviceInfo);
|
||||
return;
|
||||
}
|
||||
Intent intent = new Intent(action);
|
||||
intent.putExtra(EXTRA_BONJOUR_PEER, bonjourPeer);
|
||||
LocalBroadcastManager.getInstance(context.get()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
private static void sendBroadcast(int status, String message) {
|
||||
|
||||
Intent intent = new Intent(ACTION_STATUS);
|
||||
intent.putExtra(EXTRA_STATUS, status);
|
||||
if (!TextUtils.isEmpty(message)) {
|
||||
intent.putExtra(Intent.EXTRA_TEXT, message);
|
||||
}
|
||||
LocalBroadcastManager.getInstance(context.get()).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
private static final ServiceListener httpServiceListener = new SwapServiceListener();
|
||||
private static final ServiceListener httpsServiceListener = new SwapServiceListener();
|
||||
|
||||
private static class SwapServiceListener implements ServiceListener {
|
||||
@Override
|
||||
public void serviceAdded(ServiceEvent serviceEvent) {
|
||||
// ignored, we only need resolved info
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceRemoved(ServiceEvent serviceEvent) {
|
||||
sendBroadcast(ACTION_REMOVED, serviceEvent.getInfo());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serviceResolved(ServiceEvent serviceEvent) {
|
||||
sendBroadcast(ACTION_FOUND, serviceEvent.getInfo());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,505 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
/*
|
||||
* #%L
|
||||
* NanoHttpd-Webserver
|
||||
* %%
|
||||
* Copyright (C) 2012 - 2015 nanohttpd
|
||||
* %%
|
||||
* Redistribution and use in source and binary forms, with or without modification,
|
||||
* are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* 3. Neither the name of the nanohttpd nor the names of its contributors
|
||||
* may be used to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
|
||||
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
|
||||
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
|
||||
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
|
||||
* OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
* #L%
|
||||
*/
|
||||
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
|
||||
import org.fdroid.fdroid.BuildConfig;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FilenameFilter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.net.URLEncoder;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import javax.net.ssl.SSLServerSocketFactory;
|
||||
|
||||
import fi.iki.elonen.NanoHTTPD;
|
||||
import fi.iki.elonen.NanoHTTPD.Response.IStatus;
|
||||
|
||||
/**
|
||||
* A HTTP server for serving the files that are being swapped via WiFi, etc.
|
||||
* The only changes were to remove unneeded extras like {@code main()}, the
|
||||
* plugin interface, and custom CORS header manipulation.
|
||||
* <p>
|
||||
* This is mostly just synced from {@code SimpleWebServer.java} from NanoHTTPD.
|
||||
*
|
||||
* @see <a href="https://github.com/NanoHttpd/nanohttpd/blob/nanohttpd-project-2.3.1/webserver/src/main/java/fi/iki/elonen/SimpleWebServer.java">webserver/src/main/java/fi/iki/elonen/SimpleWebServer.java</a>
|
||||
*/
|
||||
public class LocalHTTPD extends NanoHTTPD {
|
||||
private static final String TAG = "LocalHTTPD";
|
||||
|
||||
/**
|
||||
* Default Index file names.
|
||||
*/
|
||||
public static final String[] INDEX_FILE_NAMES = {"index.html"};
|
||||
|
||||
private final WeakReference<Context> context;
|
||||
|
||||
protected List<File> rootDirs;
|
||||
|
||||
// Date format specified by RFC 7231 section 7.1.1.1.
|
||||
private static final DateFormat RFC_1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
|
||||
|
||||
static {
|
||||
RFC_1123.setLenient(false);
|
||||
RFC_1123.setTimeZone(TimeZone.getTimeZone("GMT"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure and start the webserver. This also sets the MIME Types only
|
||||
* for files that should be downloadable when a browser is used to display
|
||||
* the swap repo, rather than the F-Droid client. The other file types
|
||||
* should not be added because it could expose exploits to the browser.
|
||||
*/
|
||||
public LocalHTTPD(Context context, String hostname, int port, File webRoot, boolean useHttps) {
|
||||
super(hostname, port);
|
||||
rootDirs = Collections.singletonList(webRoot);
|
||||
this.context = new WeakReference<>(context.getApplicationContext());
|
||||
if (useHttps) {
|
||||
enableHTTPS();
|
||||
}
|
||||
MIME_TYPES = new HashMap<>(); // ignore nanohttpd's list
|
||||
MIME_TYPES.put("apk", "application/vnd.android.package-archive");
|
||||
MIME_TYPES.put("html", "text/html");
|
||||
MIME_TYPES.put("png", "image/png");
|
||||
MIME_TYPES.put("xml", "application/xml");
|
||||
}
|
||||
|
||||
private boolean canServeUri(String uri, File homeDir) {
|
||||
boolean canServeUri;
|
||||
File f = new File(homeDir, uri);
|
||||
canServeUri = f.exists();
|
||||
return canServeUri;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL-encodes everything between "/"-characters. Encodes spaces as '%20'
|
||||
* instead of '+'.
|
||||
*/
|
||||
private String encodeUri(String uri) {
|
||||
String newUri = "";
|
||||
StringTokenizer st = new StringTokenizer(uri, "/ ", true);
|
||||
while (st.hasMoreTokens()) {
|
||||
String tok = st.nextToken();
|
||||
if ("/".equals(tok)) {
|
||||
newUri += "/";
|
||||
} else if (" ".equals(tok)) {
|
||||
newUri += "%20";
|
||||
} else {
|
||||
try {
|
||||
newUri += URLEncoder.encode(tok, "UTF-8");
|
||||
} catch (UnsupportedEncodingException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return newUri;
|
||||
}
|
||||
|
||||
private String findIndexFileInDirectory(File directory) {
|
||||
for (String fileName : LocalHTTPD.INDEX_FILE_NAMES) {
|
||||
File indexFile = new File(directory, fileName);
|
||||
if (indexFile.isFile()) {
|
||||
return fileName;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected Response getForbiddenResponse(String s) {
|
||||
return newFixedLengthResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: " + s);
|
||||
}
|
||||
|
||||
protected Response getInternalErrorResponse(String s) {
|
||||
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "INTERNAL ERROR: " + s);
|
||||
}
|
||||
|
||||
protected Response getNotFoundResponse() {
|
||||
return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.");
|
||||
}
|
||||
|
||||
protected String listDirectory(String uri, File f) {
|
||||
String heading = "Directory " + uri;
|
||||
StringBuilder msg =
|
||||
new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n" + "span.dirname { font-weight: bold; }\n" + "span.filesize { font-size: 75%; }\n"
|
||||
+ "// -->\n" + "</style>" + "</head><body><h1>" + heading + "</h1>");
|
||||
|
||||
String up = null;
|
||||
if (uri.length() > 1) {
|
||||
String u = uri.substring(0, uri.length() - 1);
|
||||
int slash = u.lastIndexOf('/');
|
||||
if (slash >= 0 && slash < u.length()) {
|
||||
up = uri.substring(0, slash + 1);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> files = Arrays.asList(f.list(new FilenameFilter() {
|
||||
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
return new File(dir, name).isFile();
|
||||
}
|
||||
}));
|
||||
Collections.sort(files);
|
||||
List<String> directories = Arrays.asList(f.list(new FilenameFilter() {
|
||||
|
||||
@Override
|
||||
public boolean accept(File dir, String name) {
|
||||
return new File(dir, name).isDirectory();
|
||||
}
|
||||
}));
|
||||
Collections.sort(directories);
|
||||
if (up != null || directories.size() + files.size() > 0) {
|
||||
msg.append("<ul>");
|
||||
if (up != null || directories.size() > 0) {
|
||||
msg.append("<section class=\"directories\">");
|
||||
if (up != null) {
|
||||
msg.append("<li><a rel=\"directory\" href=\"").append(up).append("\"><span class=\"dirname\">..</span></a></li>");
|
||||
}
|
||||
for (String directory : directories) {
|
||||
String dir = directory + "/";
|
||||
msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></li>");
|
||||
}
|
||||
msg.append("</section>");
|
||||
}
|
||||
if (files.size() > 0) {
|
||||
msg.append("<section class=\"files\">");
|
||||
for (String file : files) {
|
||||
msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>");
|
||||
File curFile = new File(f, file);
|
||||
long len = curFile.length();
|
||||
msg.append(" <span class=\"filesize\">(");
|
||||
if (len < 1024) {
|
||||
msg.append(len).append(" bytes");
|
||||
} else if (len < 1024 * 1024) {
|
||||
msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
|
||||
} else {
|
||||
msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10000 % 100).append(" MB");
|
||||
}
|
||||
msg.append(")</span></li>");
|
||||
}
|
||||
msg.append("</section>");
|
||||
}
|
||||
msg.append("</ul>");
|
||||
}
|
||||
msg.append("</body></html>");
|
||||
return msg.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link Response#setKeepAlive(boolean)} alone does not seem to stop
|
||||
* setting the {@code Connection} header to {@code keep-alive}, so also
|
||||
* just directly set that header.
|
||||
*/
|
||||
public static Response addResponseHeaders(Response response) {
|
||||
response.setKeepAlive(false);
|
||||
response.setGzipEncoding(false);
|
||||
response.addHeader("Connection", "close");
|
||||
response.addHeader("Content-Security-Policy",
|
||||
"default-src 'none'; img-src 'self'; style-src 'self' 'unsafe-inline';");
|
||||
return response;
|
||||
}
|
||||
|
||||
public static Response newFixedLengthResponse(String msg) {
|
||||
return addResponseHeaders(NanoHTTPD.newFixedLengthResponse(msg));
|
||||
}
|
||||
|
||||
public static Response newFixedLengthResponse(Response.IStatus status, String mimeType,
|
||||
InputStream data, long totalBytes) {
|
||||
return addResponseHeaders(NanoHTTPD.newFixedLengthResponse(status, mimeType, data, totalBytes));
|
||||
}
|
||||
|
||||
public static Response newFixedLengthResponse(IStatus status, String mimeType, String message) {
|
||||
Response response = NanoHTTPD.newFixedLengthResponse(status, mimeType, message);
|
||||
addResponseHeaders(response);
|
||||
response.addHeader("Accept-Ranges", "bytes");
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response respond(Map<String, String> headers, IHTTPSession session, String uri) {
|
||||
return defaultRespond(headers, session, uri);
|
||||
}
|
||||
|
||||
private Response defaultRespond(Map<String, String> headers, IHTTPSession session, String uri) {
|
||||
// Remove URL arguments
|
||||
uri = uri.trim().replace(File.separatorChar, '/');
|
||||
if (uri.indexOf('?') >= 0) {
|
||||
uri = uri.substring(0, uri.indexOf('?'));
|
||||
}
|
||||
|
||||
// Prohibit getting out of current directory
|
||||
if (uri.contains("../")) {
|
||||
return getForbiddenResponse("Won't serve ../ for security reasons.");
|
||||
}
|
||||
|
||||
boolean canServeUri = false;
|
||||
File homeDir = null;
|
||||
for (int i = 0; !canServeUri && i < this.rootDirs.size(); i++) {
|
||||
homeDir = this.rootDirs.get(i);
|
||||
canServeUri = canServeUri(uri, homeDir);
|
||||
}
|
||||
if (!canServeUri) {
|
||||
return getNotFoundResponse();
|
||||
}
|
||||
|
||||
// Browsers get confused without '/' after the directory, send a
|
||||
// redirect.
|
||||
File f = new File(homeDir, uri);
|
||||
if (f.isDirectory() && !uri.endsWith("/")) {
|
||||
uri += "/";
|
||||
Response res =
|
||||
newFixedLengthResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
|
||||
res.addHeader("Location", uri);
|
||||
return res;
|
||||
}
|
||||
|
||||
if (f.isDirectory()) {
|
||||
// First look for index files (index.html, index.htm, etc) and if
|
||||
// none found, list the directory if readable.
|
||||
String indexFile = findIndexFileInDirectory(f);
|
||||
if (indexFile == null) {
|
||||
if (f.canRead()) {
|
||||
// No index file, list the directory if it is readable
|
||||
return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, listDirectory(uri, f));
|
||||
} else {
|
||||
return getForbiddenResponse("No directory listing.");
|
||||
}
|
||||
} else {
|
||||
return respond(headers, session, uri + indexFile);
|
||||
}
|
||||
}
|
||||
String mimeTypeForFile = getMimeTypeForFile(uri);
|
||||
Response response = serveFile(uri, headers, f, mimeTypeForFile);
|
||||
return response != null ? response : getNotFoundResponse();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response serve(IHTTPSession session) {
|
||||
Map<String, String> header = session.getHeaders();
|
||||
Map<String, String> parms = session.getParms();
|
||||
String uri = session.getUri();
|
||||
|
||||
if (BuildConfig.DEBUG) {
|
||||
System.out.println(session.getMethod() + " '" + uri + "' ");
|
||||
|
||||
Iterator<String> e = header.keySet().iterator();
|
||||
while (e.hasNext()) {
|
||||
String value = e.next();
|
||||
System.out.println(" HDR: '" + value + "' = '" + header.get(value) + "'");
|
||||
}
|
||||
e = parms.keySet().iterator();
|
||||
while (e.hasNext()) {
|
||||
String value = e.next();
|
||||
System.out.println(" PRM: '" + value + "' = '" + parms.get(value) + "'");
|
||||
}
|
||||
}
|
||||
|
||||
if (session.getMethod() == Method.POST) {
|
||||
try {
|
||||
session.parseBody(new HashMap<String, String>());
|
||||
} catch (IOException e) {
|
||||
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT,
|
||||
"Internal server error, check logcat on server for details.");
|
||||
} catch (ResponseException re) {
|
||||
return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
|
||||
}
|
||||
|
||||
return handlePost(session);
|
||||
}
|
||||
|
||||
for (File homeDir : this.rootDirs) {
|
||||
// Make sure we won't die of an exception later
|
||||
if (!homeDir.isDirectory()) {
|
||||
return getInternalErrorResponse("given path is not a directory (" + homeDir + ").");
|
||||
}
|
||||
}
|
||||
return respond(Collections.unmodifiableMap(header), session, uri);
|
||||
}
|
||||
|
||||
private Response handlePost(IHTTPSession session) {
|
||||
Uri uri = Uri.parse(session.getUri());
|
||||
switch (uri.getPath()) {
|
||||
case "/request-swap":
|
||||
if (!session.getParms().containsKey("repo")) {
|
||||
return newFixedLengthResponse(Response.Status.BAD_REQUEST, MIME_PLAINTEXT,
|
||||
"Requires 'repo' parameter to be posted.");
|
||||
}
|
||||
SwapWorkflowActivity.requestSwap(context.get(), session.getParms().get("repo"));
|
||||
return newFixedLengthResponse(Response.Status.OK, MIME_PLAINTEXT, "Swap request received.");
|
||||
}
|
||||
return newFixedLengthResponse("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves file from homeDir and its' subdirectories (only). Uses only URI,
|
||||
* ignores all headers and HTTP parameters.
|
||||
*/
|
||||
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
|
||||
Response res;
|
||||
try {
|
||||
// Calculate etag
|
||||
String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());
|
||||
|
||||
// Support (simple) skipping:
|
||||
long startFrom = 0;
|
||||
long endAt = -1;
|
||||
String range = header.get("range");
|
||||
if (range != null) {
|
||||
if (range.startsWith("bytes=")) {
|
||||
range = range.substring("bytes=".length());
|
||||
int minus = range.indexOf('-');
|
||||
try {
|
||||
if (minus > 0) {
|
||||
startFrom = Long.parseLong(range.substring(0, minus));
|
||||
endAt = Long.parseLong(range.substring(minus + 1));
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get if-range header. If present, it must match etag or else we
|
||||
// should ignore the range request
|
||||
String ifRange = header.get("if-range");
|
||||
boolean headerIfRangeMissingOrMatching = (ifRange == null || etag.equals(ifRange));
|
||||
|
||||
String ifNoneMatch = header.get("if-none-match");
|
||||
boolean headerIfNoneMatchPresentAndMatching = ifNoneMatch != null && ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag));
|
||||
|
||||
// Change return code and add Content-Range header when skipping is
|
||||
// requested
|
||||
long fileLen = file.length();
|
||||
|
||||
if (headerIfRangeMissingOrMatching && range != null && startFrom >= 0 && startFrom < fileLen) {
|
||||
// range request that matches current etag
|
||||
// and the startFrom of the range is satisfiable
|
||||
if (headerIfNoneMatchPresentAndMatching) {
|
||||
// range request that matches current etag
|
||||
// and the startFrom of the range is satisfiable
|
||||
// would return range from file
|
||||
// respond with not-modified
|
||||
res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
|
||||
res.addHeader("ETag", etag);
|
||||
} else {
|
||||
if (endAt < 0) {
|
||||
endAt = fileLen - 1;
|
||||
}
|
||||
long newLen = endAt - startFrom + 1;
|
||||
if (newLen < 0) {
|
||||
newLen = 0;
|
||||
}
|
||||
|
||||
FileInputStream fis = new FileInputStream(file);
|
||||
fis.skip(startFrom);
|
||||
|
||||
res = newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mime, fis, newLen);
|
||||
res.addHeader("Accept-Ranges", "bytes");
|
||||
res.addHeader("Content-Length", "" + newLen);
|
||||
res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
|
||||
res.addHeader("ETag", etag);
|
||||
res.addHeader("Last-Modified", RFC_1123.format(new Date(file.lastModified())));
|
||||
}
|
||||
} else {
|
||||
|
||||
if (headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen) {
|
||||
// return the size of the file
|
||||
// 4xx responses are not trumped by if-none-match
|
||||
res = newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
|
||||
res.addHeader("Content-Range", "bytes */" + fileLen);
|
||||
res.addHeader("ETag", etag);
|
||||
} else if (range == null && headerIfNoneMatchPresentAndMatching) {
|
||||
// full-file-fetch request
|
||||
// would return entire file
|
||||
// respond with not-modified
|
||||
res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
|
||||
res.addHeader("ETag", etag);
|
||||
} else if (!headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching) {
|
||||
// range request that doesn't match current etag
|
||||
// would return entire (different) file
|
||||
// respond with not-modified
|
||||
|
||||
res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
|
||||
res.addHeader("ETag", etag);
|
||||
} else {
|
||||
// supply the file
|
||||
res = newFixedFileResponse(file, mime);
|
||||
res.addHeader("Content-Length", "" + fileLen);
|
||||
res.addHeader("ETag", etag);
|
||||
res.addHeader("Last-Modified", RFC_1123.format(new Date(file.lastModified())));
|
||||
}
|
||||
}
|
||||
} catch (IOException ioe) {
|
||||
res = getForbiddenResponse("Reading file failed.");
|
||||
}
|
||||
|
||||
return addResponseHeaders(res);
|
||||
}
|
||||
|
||||
private Response newFixedFileResponse(File file, String mime) throws FileNotFoundException {
|
||||
Response res;
|
||||
res = newFixedLengthResponse(Response.Status.OK, mime, new FileInputStream(file), (int) file.length());
|
||||
addResponseHeaders(res);
|
||||
res.addHeader("Accept-Ranges", "bytes");
|
||||
return res;
|
||||
}
|
||||
|
||||
private void enableHTTPS() {
|
||||
try {
|
||||
LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context.get());
|
||||
SSLServerSocketFactory factory = NanoHTTPD.makeSSLSocketFactory(
|
||||
localRepoKeyStore.getKeyStore(),
|
||||
localRepoKeyStore.getKeyManagers());
|
||||
makeSecure(factory, null);
|
||||
} catch (LocalRepoKeyStore.InitException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,129 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Handler;
|
||||
import android.os.HandlerThread;
|
||||
import android.os.Message;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.BindException;
|
||||
import java.util.Random;
|
||||
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
|
||||
/**
|
||||
* Manage {@link LocalHTTPD} in a {@link HandlerThread};
|
||||
*/
|
||||
public class LocalHTTPDManager {
|
||||
private static final String TAG = "LocalHTTPDManager";
|
||||
|
||||
public static final String ACTION_STARTED = "LocalHTTPDStarted";
|
||||
public static final String ACTION_STOPPED = "LocalHTTPDStopped";
|
||||
public static final String ACTION_ERROR = "LocalHTTPDError";
|
||||
|
||||
private static final int STOP = 5709;
|
||||
|
||||
private static Handler handler;
|
||||
private static volatile HandlerThread handlerThread;
|
||||
private static LocalHTTPD localHttpd;
|
||||
|
||||
public static void start(Context context) {
|
||||
start(context, Preferences.get().isLocalRepoHttpsEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Testable version, not for regular use.
|
||||
*
|
||||
* @see #start(Context)
|
||||
*/
|
||||
static void start(final Context context, final boolean useHttps) {
|
||||
if (handlerThread != null && handlerThread.isAlive()) {
|
||||
Log.w(TAG, "handlerThread is already running, doing nothing!");
|
||||
return;
|
||||
}
|
||||
|
||||
handlerThread = new HandlerThread("LocalHTTPD", Process.THREAD_PRIORITY_LESS_FAVORABLE) {
|
||||
@Override
|
||||
protected void onLooperPrepared() {
|
||||
localHttpd = new LocalHTTPD(
|
||||
context,
|
||||
FDroidApp.ipAddressString,
|
||||
FDroidApp.port,
|
||||
context.getFilesDir(),
|
||||
useHttps);
|
||||
try {
|
||||
localHttpd.start();
|
||||
Intent intent = new Intent(ACTION_STARTED);
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
|
||||
} catch (BindException e) {
|
||||
int prev = FDroidApp.port;
|
||||
FDroidApp.port = FDroidApp.port + new Random().nextInt(1111);
|
||||
WifiStateChangeService.start(context, null);
|
||||
Intent intent = new Intent(ACTION_ERROR);
|
||||
intent.putExtra(Intent.EXTRA_TEXT,
|
||||
"port " + prev + " occupied, trying on " + FDroidApp.port + ": ("
|
||||
+ e.getLocalizedMessage() + ")");
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
Intent intent = new Intent(ACTION_ERROR);
|
||||
intent.putExtra(Intent.EXTRA_TEXT, e.getLocalizedMessage());
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
|
||||
}
|
||||
}
|
||||
};
|
||||
handlerThread.start();
|
||||
handler = new Handler(handlerThread.getLooper()) {
|
||||
@Override
|
||||
public void handleMessage(Message msg) {
|
||||
localHttpd.stop();
|
||||
handlerThread.quit();
|
||||
handlerThread = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static void stop(Context context) {
|
||||
if (handler == null || handlerThread == null || !handlerThread.isAlive()) {
|
||||
Log.w(TAG, "handlerThread is already stopped, doing nothing!");
|
||||
handlerThread = null;
|
||||
return;
|
||||
}
|
||||
handler.sendEmptyMessage(STOP);
|
||||
Intent stoppedIntent = new Intent(ACTION_STOPPED);
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(stoppedIntent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run {@link #stop(Context)}, wait for it to actually stop, then run
|
||||
* {@link #start(Context)}.
|
||||
*/
|
||||
public static void restart(Context context) {
|
||||
restart(context, Preferences.get().isLocalRepoHttpsEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Testable version, not for regular use.
|
||||
*
|
||||
* @see #restart(Context)
|
||||
*/
|
||||
static void restart(Context context, boolean useHttps) {
|
||||
stop(context);
|
||||
try {
|
||||
handlerThread.join(10000);
|
||||
} catch (InterruptedException | NullPointerException e) {
|
||||
// ignored
|
||||
}
|
||||
start(context, useHttps);
|
||||
}
|
||||
|
||||
public static boolean isAlive() {
|
||||
return handlerThread != null && handlerThread.isAlive();
|
||||
}
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.app.IntentService;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Process;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
|
||||
/**
|
||||
* Handles setting up and generating the local repo used to swap apps, including
|
||||
* the {@code index.jar}, the symlinks to the shared APKs, etc.
|
||||
* <p/>
|
||||
* The work is done in a {@link Thread} so that new incoming {@code Intents}
|
||||
* are not blocked by processing. A new {@code Intent} immediately nullifies
|
||||
* the current state because it means the user has chosen a different set of
|
||||
* apps. That is also enforced here since new {@code Intent}s with the same
|
||||
* {@link Set} of apps as the current one are ignored. Having the
|
||||
* {@code Thread} also makes it easy to kill work that is in progress.
|
||||
*/
|
||||
public class LocalRepoService extends IntentService {
|
||||
public static final String TAG = "LocalRepoService";
|
||||
|
||||
public static final String ACTION_CREATE = "org.fdroid.fdroid.nearby.action.CREATE";
|
||||
public static final String EXTRA_PACKAGE_NAMES = "org.fdroid.fdroid.nearby.extra.PACKAGE_NAMES";
|
||||
|
||||
public static final String ACTION_STATUS = "localRepoStatusAction";
|
||||
public static final String EXTRA_STATUS = "localRepoStatusExtra";
|
||||
public static final int STATUS_STARTED = 0;
|
||||
public static final int STATUS_PROGRESS = 1;
|
||||
public static final int STATUS_ERROR = 2;
|
||||
|
||||
private String[] currentlyProcessedApps = new String[0];
|
||||
|
||||
private GenerateLocalRepoThread thread;
|
||||
|
||||
public LocalRepoService() {
|
||||
super("LocalRepoService");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a skeleton swap repo with only F-Droid itself in it
|
||||
*/
|
||||
public static void create(Context context) {
|
||||
create(context, Collections.singleton(context.getPackageName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the local repo with the included {@code packageNames}
|
||||
*/
|
||||
public static void create(Context context, Set<String> packageNames) {
|
||||
Intent intent = new Intent(context, LocalRepoService.class);
|
||||
intent.setAction(ACTION_CREATE);
|
||||
intent.putExtra(EXTRA_PACKAGE_NAMES, packageNames.toArray(new String[0]));
|
||||
context.startService(intent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
||||
String[] packageNames = intent.getStringArrayExtra(EXTRA_PACKAGE_NAMES);
|
||||
if (packageNames == null || packageNames.length == 0) {
|
||||
Utils.debugLog(TAG, "no packageNames found, quiting");
|
||||
return;
|
||||
}
|
||||
Arrays.sort(packageNames);
|
||||
|
||||
if (Arrays.equals(currentlyProcessedApps, packageNames)) {
|
||||
Utils.debugLog(TAG, "packageNames list unchanged, quiting");
|
||||
return;
|
||||
}
|
||||
currentlyProcessedApps = packageNames;
|
||||
|
||||
if (thread != null) {
|
||||
thread.interrupt();
|
||||
}
|
||||
thread = new GenerateLocalRepoThread();
|
||||
thread.start();
|
||||
}
|
||||
|
||||
private class GenerateLocalRepoThread extends Thread {
|
||||
private static final String TAG = "GenerateLocalRepoThread";
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LOWEST);
|
||||
runProcess(LocalRepoService.this, currentlyProcessedApps);
|
||||
}
|
||||
}
|
||||
|
||||
public static void runProcess(Context context, String[] selectedApps) {
|
||||
try {
|
||||
final LocalRepoManager lrm = LocalRepoManager.get(context);
|
||||
broadcast(context, STATUS_PROGRESS, R.string.deleting_repo);
|
||||
lrm.deleteRepo();
|
||||
for (String app : selectedApps) {
|
||||
broadcast(context, STATUS_PROGRESS, context.getString(R.string.adding_apks_format, app));
|
||||
lrm.addApp(context, app);
|
||||
}
|
||||
String urlString = Utils.getSharingUri(FDroidApp.repo).toString();
|
||||
lrm.writeIndexPage(urlString);
|
||||
broadcast(context, STATUS_PROGRESS, R.string.writing_index_jar);
|
||||
lrm.writeIndexJar();
|
||||
broadcast(context, STATUS_PROGRESS, R.string.linking_apks);
|
||||
lrm.copyApksToRepo();
|
||||
broadcast(context, STATUS_PROGRESS, R.string.copying_icons);
|
||||
// run the icon copy without progress, its not a blocker
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LOWEST);
|
||||
lrm.copyIconsToRepo();
|
||||
}
|
||||
}.start();
|
||||
|
||||
broadcast(context, STATUS_STARTED, null);
|
||||
} catch (IOException | XmlPullParserException | LocalRepoKeyStore.InitException e) {
|
||||
broadcast(context, STATUS_ERROR, e.getLocalizedMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate Android style broadcast {@link Intent}s to {@code PrepareSwapRepo}
|
||||
*/
|
||||
static void broadcast(Context context, int status, String message) {
|
||||
Intent intent = new Intent(ACTION_STATUS);
|
||||
intent.putExtra(EXTRA_STATUS, status);
|
||||
if (message != null) {
|
||||
intent.putExtra(Intent.EXTRA_TEXT, message);
|
||||
}
|
||||
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
|
||||
}
|
||||
|
||||
static void broadcast(Context context, int status, int resId) {
|
||||
broadcast(context, status, context.getString(resId));
|
||||
}
|
||||
}
|
@ -1,175 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.Manifest;
|
||||
import android.app.IntentService;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.IndexUpdater;
|
||||
import org.fdroid.fdroid.IndexV1Updater;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
/**
|
||||
* An {@link IntentService} subclass for scanning removable "external storage"
|
||||
* for F-Droid package repos, e.g. SD Cards. This is intended to support
|
||||
* sharable package repos, so it ignores non-removable storage, like the fake
|
||||
* emulated sdcard from devices with only built-in storage. This method will
|
||||
* only ever allow for reading repos, never writing. It also will not work
|
||||
* for removeable storage devices plugged in via USB, since do not show up as
|
||||
* "External Storage"
|
||||
* <p>
|
||||
* Scanning the removable storage requires that the user allowed it. This
|
||||
* requires both the {@link org.fdroid.fdroid.Preferences#isScanRemovableStorageEnabled()}
|
||||
* and the {@link android.Manifest.permission#READ_EXTERNAL_STORAGE}
|
||||
* permission to be enabled.
|
||||
*
|
||||
* @see TreeUriScannerIntentService TreeUri method for writing repos to be shared
|
||||
* @see <a href="https://stackoverflow.com/a/40201333">Universal way to write to external SD card on Android</a>
|
||||
* @see <a href="https://commonsware.com/blog/2017/11/14/storage-situation-external-storage.html"> The Storage Situation: External Storage </a>
|
||||
*/
|
||||
public class SDCardScannerService extends IntentService {
|
||||
public static final String TAG = "SDCardScannerService";
|
||||
|
||||
private static final String ACTION_SCAN = "org.fdroid.fdroid.nearby.SCAN";
|
||||
|
||||
private static final List<String> SKIP_DIRS = Arrays.asList(".android_secure", "LOST.DIR");
|
||||
|
||||
public SDCardScannerService() {
|
||||
super("SDCardScannerService");
|
||||
}
|
||||
|
||||
public static void scan(Context context) {
|
||||
Intent intent = new Intent(context, SDCardScannerService.class);
|
||||
intent.setAction(ACTION_SCAN);
|
||||
context.startService(intent);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
if (intent == null || !ACTION_SCAN.equals(intent.getAction())) {
|
||||
return;
|
||||
}
|
||||
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
||||
|
||||
HashSet<File> files = new HashSet<>();
|
||||
if (Build.VERSION.SDK_INT < 21) {
|
||||
if (Environment.isExternalStorageRemovable()) {
|
||||
File sdcard = Environment.getExternalStorageDirectory();
|
||||
String state = Environment.getExternalStorageState();
|
||||
Collections.addAll(files, checkExternalStorage(sdcard, state));
|
||||
}
|
||||
} else {
|
||||
for (File f : getExternalFilesDirs(null)) {
|
||||
Log.i(TAG, "getExternalFilesDirs " + f);
|
||||
if (f == null || !f.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
Log.i(TAG, "getExternalFilesDirs " + f);
|
||||
if (Environment.isExternalStorageRemovable(f)) {
|
||||
String state = Environment.getExternalStorageState(f);
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
|
||||
== PackageManager.PERMISSION_GRANTED) {
|
||||
// remove Android/data/org.fdroid.fdroid/files to get root
|
||||
File sdcard = f.getParentFile().getParentFile().getParentFile().getParentFile();
|
||||
Collections.addAll(files, checkExternalStorage(sdcard, state));
|
||||
} else {
|
||||
Collections.addAll(files, checkExternalStorage(f, state));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.i(TAG, "sdcard files " + files.toString());
|
||||
ArrayList<String> filesList = new ArrayList<>();
|
||||
for (File dir : files) {
|
||||
if (!dir.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
searchDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
private File[] checkExternalStorage(File sdcard, String state) {
|
||||
File[] files = null;
|
||||
if (sdcard != null &&
|
||||
(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) || Environment.MEDIA_MOUNTED.equals(state))) {
|
||||
files = sdcard.listFiles();
|
||||
}
|
||||
|
||||
if (files == null) {
|
||||
Utils.debugLog(TAG, "checkExternalStorage returned blank, F-Droid probaby doesn't have Storage perm!");
|
||||
return new File[0];
|
||||
} else {
|
||||
return files;
|
||||
}
|
||||
}
|
||||
|
||||
private void searchDirectory(File dir) {
|
||||
if (SKIP_DIRS.contains(dir.getName())) {
|
||||
return;
|
||||
}
|
||||
File[] files = dir.listFiles();
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
searchDirectory(file);
|
||||
} else {
|
||||
if (IndexV1Updater.SIGNED_FILE_NAME.equals(file.getName())) {
|
||||
registerRepo(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void registerRepo(File file) {
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
inputStream = new FileInputStream(file);
|
||||
TreeUriScannerIntentService.registerRepo(this, inputStream, Uri.fromFile(file.getParentFile()));
|
||||
} catch (IOException | IndexUpdater.SigningException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
Utils.closeQuietly(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,248 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.net.wifi.WifiConfiguration;
|
||||
import android.text.TextUtils;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.CompoundButton;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.ListView;
|
||||
import android.widget.ProgressBar;
|
||||
import android.widget.TextView;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.nearby.peers.Peer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import com.google.android.material.switchmaterial.SwitchMaterial;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
import cc.mvdan.accesspoint.WifiApControl;
|
||||
|
||||
@SuppressWarnings("LineLength")
|
||||
public class StartSwapView extends SwapView {
|
||||
private static final String TAG = "StartSwapView";
|
||||
|
||||
public StartSwapView(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public StartSwapView(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public StartSwapView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
@TargetApi(21)
|
||||
public StartSwapView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
class PeopleNearbyAdapter extends ArrayAdapter<Peer> {
|
||||
|
||||
PeopleNearbyAdapter(Context context) {
|
||||
super(context, 0, new ArrayList<Peer>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public View getView(int position, View convertView, ViewGroup parent) {
|
||||
if (convertView == null) {
|
||||
convertView = LayoutInflater.from(getContext())
|
||||
.inflate(R.layout.swap_peer_list_item, parent, false);
|
||||
}
|
||||
|
||||
Peer peer = getItem(position);
|
||||
((TextView) convertView.findViewById(R.id.peer_name)).setText(peer.getName());
|
||||
((ImageView) convertView.findViewById(R.id.icon))
|
||||
.setImageDrawable(ContextCompat.getDrawable(getContext(), peer.getIcon()));
|
||||
|
||||
return convertView;
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable /* Emulators typically don't have bluetooth adapters */
|
||||
private final BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
|
||||
|
||||
private SwitchMaterial bluetoothSwitch;
|
||||
private TextView viewBluetoothId;
|
||||
private TextView textBluetoothVisible;
|
||||
private TextView viewWifiId;
|
||||
private TextView viewWifiNetwork;
|
||||
private TextView peopleNearbyText;
|
||||
private ListView peopleNearbyList;
|
||||
private ProgressBar peopleNearbyProgress;
|
||||
|
||||
private PeopleNearbyAdapter peopleNearbyAdapter;
|
||||
|
||||
/**
|
||||
* Remove relevant listeners/subscriptions/etc so that they do not receive and process events
|
||||
* when this view is not in use.
|
||||
* <p>
|
||||
*/
|
||||
@Override
|
||||
protected void onDetachedFromWindow() {
|
||||
super.onDetachedFromWindow();
|
||||
if (bluetoothSwitch != null) {
|
||||
bluetoothSwitch.setOnCheckedChangeListener(null);
|
||||
}
|
||||
|
||||
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(onWifiNetworkChanged);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onFinishInflate() {
|
||||
super.onFinishInflate();
|
||||
|
||||
uiInitPeers();
|
||||
uiInitBluetooth();
|
||||
uiInitWifi();
|
||||
uiInitButtons();
|
||||
|
||||
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
|
||||
onWifiNetworkChanged, new IntentFilter(WifiStateChangeService.BROADCAST));
|
||||
}
|
||||
|
||||
private final BroadcastReceiver onWifiNetworkChanged = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
uiUpdateWifiNetwork();
|
||||
}
|
||||
};
|
||||
|
||||
private void uiInitButtons() {
|
||||
findViewById(R.id.btn_send_fdroid).setOnClickListener(new OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
getActivity().sendFDroid();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the list of nearby peers with an adapter, and hide or show it and the associated
|
||||
* message for when no peers are nearby depending on what is happening.
|
||||
*/
|
||||
private void uiInitPeers() {
|
||||
|
||||
peopleNearbyText = (TextView) findViewById(R.id.text_people_nearby);
|
||||
peopleNearbyList = (ListView) findViewById(R.id.list_people_nearby);
|
||||
peopleNearbyProgress = (ProgressBar) findViewById(R.id.searching_people_nearby);
|
||||
|
||||
peopleNearbyAdapter = new PeopleNearbyAdapter(getContext());
|
||||
peopleNearbyList.setAdapter(peopleNearbyAdapter);
|
||||
peopleNearbyAdapter.addAll(getActivity().getSwapService().getActivePeers());
|
||||
|
||||
peopleNearbyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
|
||||
Peer peer = peopleNearbyAdapter.getItem(position);
|
||||
onPeerSelected(peer);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void uiShowNotSearchingForPeers() {
|
||||
peopleNearbyProgress.setVisibility(View.GONE);
|
||||
if (peopleNearbyList.getAdapter().getCount() > 0) {
|
||||
peopleNearbyText.setText(getContext().getString(R.string.swap_people_nearby));
|
||||
} else {
|
||||
peopleNearbyText.setText(getContext().getString(R.string.swap_no_peers_nearby));
|
||||
}
|
||||
}
|
||||
|
||||
private void uiInitBluetooth() {
|
||||
if (bluetooth != null) {
|
||||
|
||||
viewBluetoothId = (TextView) findViewById(R.id.device_id_bluetooth);
|
||||
viewBluetoothId.setText(bluetooth.getName());
|
||||
viewBluetoothId.setVisibility(bluetooth.isEnabled() ? View.VISIBLE : View.GONE);
|
||||
|
||||
textBluetoothVisible = findViewById(R.id.bluetooth_visible);
|
||||
|
||||
bluetoothSwitch = (SwitchMaterial) findViewById(R.id.switch_bluetooth);
|
||||
bluetoothSwitch.setOnCheckedChangeListener(onBluetoothSwitchToggled);
|
||||
bluetoothSwitch.setChecked(SwapService.getBluetoothVisibleUserPreference());
|
||||
bluetoothSwitch.setEnabled(true);
|
||||
bluetoothSwitch.setOnCheckedChangeListener(onBluetoothSwitchToggled);
|
||||
} else {
|
||||
findViewById(R.id.bluetooth_info).setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
private final CompoundButton.OnCheckedChangeListener onBluetoothSwitchToggled = new CompoundButton.OnCheckedChangeListener() {
|
||||
@Override
|
||||
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
|
||||
if (isChecked) {
|
||||
Utils.debugLog(TAG, "Received onCheckChanged(true) for Bluetooth swap, prompting user as to whether they want to enable Bluetooth.");
|
||||
getActivity().startBluetoothSwap();
|
||||
textBluetoothVisible.setText(R.string.swap_visible_bluetooth);
|
||||
viewBluetoothId.setVisibility(View.VISIBLE);
|
||||
Utils.debugLog(TAG, "Received onCheckChanged(true) for Bluetooth swap (prompting user or setup Bluetooth complete)");
|
||||
// TODO: When they deny the request for enabling bluetooth, we need to disable this switch...
|
||||
} else {
|
||||
Utils.debugLog(TAG, "Received onCheckChanged(false) for Bluetooth swap, disabling Bluetooth swap.");
|
||||
BluetoothManager.stop(getContext());
|
||||
textBluetoothVisible.setText(R.string.swap_not_visible_bluetooth);
|
||||
viewBluetoothId.setVisibility(View.GONE);
|
||||
Utils.debugLog(TAG, "Received onCheckChanged(false) for Bluetooth swap, Bluetooth swap disabled successfully.");
|
||||
}
|
||||
SwapService.putBluetoothVisibleUserPreference(isChecked);
|
||||
}
|
||||
};
|
||||
|
||||
private void uiInitWifi() {
|
||||
|
||||
viewWifiId = (TextView) findViewById(R.id.device_id_wifi);
|
||||
viewWifiNetwork = (TextView) findViewById(R.id.wifi_network);
|
||||
|
||||
uiUpdateWifiNetwork();
|
||||
}
|
||||
|
||||
private void uiUpdateWifiNetwork() {
|
||||
|
||||
viewWifiId.setText(FDroidApp.ipAddressString);
|
||||
viewWifiId.setVisibility(TextUtils.isEmpty(FDroidApp.ipAddressString) ? View.GONE : View.VISIBLE);
|
||||
|
||||
WifiApControl wifiAp = WifiApControl.getInstance(getActivity());
|
||||
if (wifiAp != null && wifiAp.isWifiApEnabled()) {
|
||||
WifiConfiguration config = wifiAp.getConfiguration();
|
||||
TextView textWifiVisible = findViewById(R.id.wifi_visible);
|
||||
if (textWifiVisible != null) {
|
||||
textWifiVisible.setText(R.string.swap_visible_hotspot);
|
||||
}
|
||||
Context context = getContext();
|
||||
if (config == null) {
|
||||
viewWifiNetwork.setText(context.getString(R.string.swap_active_hotspot,
|
||||
context.getString(R.string.swap_blank_wifi_ssid)));
|
||||
} else {
|
||||
viewWifiNetwork.setText(context.getString(R.string.swap_active_hotspot, config.SSID));
|
||||
}
|
||||
} else if (TextUtils.isEmpty(FDroidApp.ssid)) {
|
||||
// not connected to or setup with any wifi network
|
||||
viewWifiNetwork.setText(R.string.swap_no_wifi_network);
|
||||
} else {
|
||||
// connected to a regular wifi network
|
||||
viewWifiNetwork.setText(FDroidApp.ssid);
|
||||
}
|
||||
}
|
||||
|
||||
private void onPeerSelected(Peer peer) {
|
||||
getActivity().swapWith(peer);
|
||||
}
|
||||
}
|
@ -1,647 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.SharedPreferences;
|
||||
import android.net.Uri;
|
||||
import android.net.wifi.WifiManager;
|
||||
import android.os.IBinder;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.app.NotificationCompat;
|
||||
import androidx.core.app.ServiceCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.NotificationHelper;
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.UpdateService;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.data.Repo;
|
||||
import org.fdroid.fdroid.data.RepoProvider;
|
||||
import org.fdroid.fdroid.data.Schema;
|
||||
import org.fdroid.fdroid.nearby.peers.Peer;
|
||||
import org.fdroid.fdroid.net.Downloader;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
import cc.mvdan.accesspoint.WifiApControl;
|
||||
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.rxjava3.core.Completable;
|
||||
import io.reactivex.rxjava3.disposables.CompositeDisposable;
|
||||
import io.reactivex.rxjava3.schedulers.Schedulers;
|
||||
|
||||
/**
|
||||
* Central service which manages all of the different moving parts of swap which are required
|
||||
* to enable p2p swapping of apps.
|
||||
*/
|
||||
public class SwapService extends Service {
|
||||
private static final String TAG = "SwapService";
|
||||
|
||||
private static final String SHARED_PREFERENCES = "swap-state";
|
||||
private static final String KEY_APPS_TO_SWAP = "appsToSwap";
|
||||
private static final String KEY_BLUETOOTH_ENABLED = "bluetoothEnabled";
|
||||
private static final String KEY_WIFI_ENABLED = "wifiEnabled";
|
||||
private static final String KEY_HOTSPOT_ACTIVATED = "hotspotEnabled";
|
||||
private static final String KEY_BLUETOOTH_ENABLED_BEFORE_SWAP = "bluetoothEnabledBeforeSwap";
|
||||
private static final String KEY_BLUETOOTH_NAME_BEFORE_SWAP = "bluetoothNameBeforeSwap";
|
||||
private static final String KEY_WIFI_ENABLED_BEFORE_SWAP = "wifiEnabledBeforeSwap";
|
||||
private static final String KEY_HOTSPOT_ACTIVATED_BEFORE_SWAP = "hotspotEnabledBeforeSwap";
|
||||
|
||||
@NonNull
|
||||
private final Set<String> appsToSwap = new HashSet<>();
|
||||
private final Set<Peer> activePeers = new HashSet<>();
|
||||
|
||||
private static LocalBroadcastManager localBroadcastManager;
|
||||
private static SharedPreferences swapPreferences;
|
||||
private static BluetoothAdapter bluetoothAdapter;
|
||||
private static WifiManager wifiManager;
|
||||
private static Timer pollConnectedSwapRepoTimer;
|
||||
|
||||
public static void stop(Context context) {
|
||||
Intent intent = new Intent(context, SwapService.class);
|
||||
context.stopService(intent);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Set<String> getAppsToSwap() {
|
||||
return appsToSwap;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Set<Peer> getActivePeers() {
|
||||
return activePeers;
|
||||
}
|
||||
|
||||
public void connectToPeer() {
|
||||
if (getPeer() == null) {
|
||||
throw new IllegalStateException("Cannot connect to peer, no peer has been selected.");
|
||||
}
|
||||
connectTo(getPeer());
|
||||
if (LocalHTTPDManager.isAlive() && getPeer().shouldPromptForSwapBack()) {
|
||||
askServerToSwapWithUs(peerRepo);
|
||||
}
|
||||
}
|
||||
|
||||
public void connectTo(@NonNull Peer peer) {
|
||||
if (peer != this.peer) {
|
||||
Log.e(TAG, "Oops, got a different peer to swap with than initially planned.");
|
||||
}
|
||||
peerRepo = ensureRepoExists(peer);
|
||||
UpdateService.updateRepoNow(this, peer.getRepoAddress());
|
||||
}
|
||||
|
||||
private Repo ensureRepoExists(@NonNull Peer peer) {
|
||||
// TODO: newRepoConfig.getParsedUri() will include a fingerprint, which may not match with
|
||||
// the repos address in the database. Not sure on best behaviour in this situation.
|
||||
Repo repo = RepoProvider.Helper.findByAddress(this, peer.getRepoAddress());
|
||||
if (repo == null) {
|
||||
ContentValues values = new ContentValues(6);
|
||||
|
||||
// The name/description is not really required, as swap repos are not shown in the
|
||||
// "Manage repos" UI on other device. Doesn't hurt to put something there though,
|
||||
// on the off chance that somebody is looking through the sqlite database which
|
||||
// contains the repos...
|
||||
values.put(Schema.RepoTable.Cols.NAME, peer.getName());
|
||||
values.put(Schema.RepoTable.Cols.ADDRESS, peer.getRepoAddress());
|
||||
values.put(Schema.RepoTable.Cols.DESCRIPTION, "");
|
||||
String fingerprint = peer.getFingerprint();
|
||||
if (!TextUtils.isEmpty(fingerprint)) {
|
||||
values.put(Schema.RepoTable.Cols.FINGERPRINT, peer.getFingerprint());
|
||||
}
|
||||
values.put(Schema.RepoTable.Cols.IN_USE, 1);
|
||||
values.put(Schema.RepoTable.Cols.IS_SWAP, true);
|
||||
Uri uri = RepoProvider.Helper.insert(this, values);
|
||||
repo = RepoProvider.Helper.get(this, uri);
|
||||
}
|
||||
|
||||
return repo;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Repo getPeerRepo() {
|
||||
return peerRepo;
|
||||
}
|
||||
|
||||
// =================================================
|
||||
// Have selected a specific peer to swap with
|
||||
// (Rather than showing a generic QR code to scan)
|
||||
// =================================================
|
||||
|
||||
@Nullable
|
||||
private Peer peer;
|
||||
|
||||
@Nullable
|
||||
private Repo peerRepo;
|
||||
|
||||
public void swapWith(Peer peer) {
|
||||
this.peer = peer;
|
||||
}
|
||||
|
||||
public void addCurrentPeerToActive() {
|
||||
activePeers.add(peer);
|
||||
}
|
||||
|
||||
public void removeCurrentPeerFromActive() {
|
||||
activePeers.remove(peer);
|
||||
}
|
||||
|
||||
public boolean isConnectingWithPeer() {
|
||||
return peer != null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Peer getPeer() {
|
||||
return peer;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// Remember apps user wants to swap
|
||||
// ==========================================
|
||||
|
||||
private void persistAppsToSwap() {
|
||||
swapPreferences.edit().putString(KEY_APPS_TO_SWAP, serializePackages(appsToSwap)).apply();
|
||||
}
|
||||
|
||||
/**
|
||||
* Replacement for {@link android.content.SharedPreferences.Editor#putStringSet(String, Set)}
|
||||
* which is only available in API >= 11.
|
||||
* Package names are reverse-DNS-style, so they should only have alpha numeric values. Thus,
|
||||
* this uses a comma as the separator.
|
||||
*
|
||||
* @see SwapService#deserializePackages(String)
|
||||
*/
|
||||
private static String serializePackages(Set<String> packages) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (String pkg : packages) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(',');
|
||||
}
|
||||
sb.append(pkg);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @see SwapService#deserializePackages(String)
|
||||
*/
|
||||
private static Set<String> deserializePackages(String packages) {
|
||||
Set<String> set = new HashSet<>();
|
||||
if (!TextUtils.isEmpty(packages)) {
|
||||
Collections.addAll(set, packages.split(","));
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
public void ensureFDroidSelected() {
|
||||
String fdroid = getPackageName();
|
||||
if (!hasSelectedPackage(fdroid)) {
|
||||
selectPackage(fdroid);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasSelectedPackage(String packageName) {
|
||||
return appsToSwap.contains(packageName);
|
||||
}
|
||||
|
||||
public void selectPackage(String packageName) {
|
||||
appsToSwap.add(packageName);
|
||||
persistAppsToSwap();
|
||||
}
|
||||
|
||||
public void deselectPackage(String packageName) {
|
||||
if (appsToSwap.contains(packageName)) {
|
||||
appsToSwap.remove(packageName);
|
||||
}
|
||||
persistAppsToSwap();
|
||||
}
|
||||
|
||||
public static boolean getBluetoothVisibleUserPreference() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_BLUETOOTH_ENABLED, false);
|
||||
}
|
||||
|
||||
public static void putBluetoothVisibleUserPreference(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_BLUETOOTH_ENABLED, visible).apply();
|
||||
}
|
||||
|
||||
public static boolean getWifiVisibleUserPreference() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_WIFI_ENABLED, false);
|
||||
}
|
||||
|
||||
public static void putWifiVisibleUserPreference(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_WIFI_ENABLED, visible).apply();
|
||||
}
|
||||
|
||||
public static boolean getHotspotActivatedUserPreference() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_HOTSPOT_ACTIVATED, false);
|
||||
}
|
||||
|
||||
public static void putHotspotActivatedUserPreference(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_HOTSPOT_ACTIVATED, visible).apply();
|
||||
}
|
||||
|
||||
public static boolean wasBluetoothEnabledBeforeSwap() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_BLUETOOTH_ENABLED_BEFORE_SWAP, false);
|
||||
}
|
||||
|
||||
public static void putBluetoothEnabledBeforeSwap(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_BLUETOOTH_ENABLED_BEFORE_SWAP, visible).apply();
|
||||
}
|
||||
|
||||
public static String getBluetoothNameBeforeSwap() {
|
||||
return swapPreferences.getString(SwapService.KEY_BLUETOOTH_NAME_BEFORE_SWAP, null);
|
||||
}
|
||||
|
||||
public static void putBluetoothNameBeforeSwap(String name) {
|
||||
swapPreferences.edit().putString(SwapService.KEY_BLUETOOTH_NAME_BEFORE_SWAP, name).apply();
|
||||
}
|
||||
|
||||
public static boolean wasWifiEnabledBeforeSwap() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_WIFI_ENABLED_BEFORE_SWAP, false);
|
||||
}
|
||||
|
||||
public static void putWifiEnabledBeforeSwap(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_WIFI_ENABLED_BEFORE_SWAP, visible).apply();
|
||||
}
|
||||
|
||||
public static boolean wasHotspotEnabledBeforeSwap() {
|
||||
return swapPreferences.getBoolean(SwapService.KEY_HOTSPOT_ACTIVATED_BEFORE_SWAP, false);
|
||||
}
|
||||
|
||||
public static void putHotspotEnabledBeforeSwap(boolean visible) {
|
||||
swapPreferences.edit().putBoolean(SwapService.KEY_HOTSPOT_ACTIVATED_BEFORE_SWAP, visible).apply();
|
||||
}
|
||||
|
||||
private static final int NOTIFICATION = 1;
|
||||
|
||||
private final Binder binder = new Binder();
|
||||
|
||||
private static final int TIMEOUT = 15 * 60 * 1000; // 15 mins
|
||||
|
||||
/**
|
||||
* Used to automatically turn of swapping after a defined amount of time (15 mins).
|
||||
*/
|
||||
@Nullable
|
||||
private Timer timer;
|
||||
|
||||
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
|
||||
|
||||
public class Binder extends android.os.Binder {
|
||||
public SwapService getService() {
|
||||
return SwapService.this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
startForeground(NOTIFICATION, createNotification());
|
||||
localBroadcastManager = LocalBroadcastManager.getInstance(this);
|
||||
swapPreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
|
||||
|
||||
LocalHTTPDManager.start(this);
|
||||
|
||||
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
if (bluetoothAdapter != null) {
|
||||
SwapService.putBluetoothEnabledBeforeSwap(bluetoothAdapter.isEnabled());
|
||||
if (bluetoothAdapter.isEnabled()) {
|
||||
BluetoothManager.start(this);
|
||||
}
|
||||
registerReceiver(bluetoothScanModeChanged,
|
||||
new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
|
||||
}
|
||||
|
||||
wifiManager = ContextCompat.getSystemService(getApplicationContext(), WifiManager.class);
|
||||
if (wifiManager != null) {
|
||||
SwapService.putWifiEnabledBeforeSwap(wifiManager.isWifiEnabled());
|
||||
}
|
||||
|
||||
appsToSwap.addAll(deserializePackages(swapPreferences.getString(KEY_APPS_TO_SWAP, "")));
|
||||
|
||||
Preferences.get().registerLocalRepoHttpsListeners(httpsEnabledListener);
|
||||
|
||||
localBroadcastManager.registerReceiver(onWifiChange, new IntentFilter(WifiStateChangeService.BROADCAST));
|
||||
localBroadcastManager.registerReceiver(bluetoothStatus, new IntentFilter(BluetoothManager.ACTION_STATUS));
|
||||
localBroadcastManager.registerReceiver(bluetoothPeerFound, new IntentFilter(BluetoothManager.ACTION_FOUND));
|
||||
localBroadcastManager.registerReceiver(bonjourPeerFound, new IntentFilter(BonjourManager.ACTION_FOUND));
|
||||
localBroadcastManager.registerReceiver(bonjourPeerRemoved, new IntentFilter(BonjourManager.ACTION_REMOVED));
|
||||
localBroadcastManager.registerReceiver(localRepoStatus, new IntentFilter(LocalRepoService.ACTION_STATUS));
|
||||
|
||||
if (getHotspotActivatedUserPreference()) {
|
||||
WifiApControl wifiApControl = WifiApControl.getInstance(this);
|
||||
if (wifiApControl != null) {
|
||||
wifiApControl.enable();
|
||||
}
|
||||
} else if (getWifiVisibleUserPreference()) {
|
||||
if (wifiManager != null) {
|
||||
wifiManager.setWifiEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
BonjourManager.start(this);
|
||||
BonjourManager.setVisible(this, getWifiVisibleUserPreference() || getHotspotActivatedUserPreference());
|
||||
}
|
||||
|
||||
private void askServerToSwapWithUs(final Repo repo) {
|
||||
compositeDisposable.add(
|
||||
Completable.fromAction(() -> {
|
||||
String swapBackUri = Utils.getLocalRepoUri(FDroidApp.repo).toString();
|
||||
HttpURLConnection conn = null;
|
||||
try {
|
||||
URL url = new URL(repo.address.replace("/fdroid/repo", "/request-swap"));
|
||||
conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setDoInput(true);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
try (OutputStream outputStream = conn.getOutputStream();
|
||||
OutputStreamWriter writer = new OutputStreamWriter(outputStream)) {
|
||||
writer.write("repo=" + swapBackUri);
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
int responseCode = conn.getResponseCode();
|
||||
Utils.debugLog(TAG, "Asking server at " + repo.address + " to swap with us in return (by " +
|
||||
"POSTing to \"/request-swap\" with repo \"" + swapBackUri + "\"): " + responseCode);
|
||||
} finally {
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribeOn(Schedulers.io())
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.doOnError(e -> {
|
||||
Intent intent = new Intent(Downloader.ACTION_INTERRUPTED);
|
||||
intent.setData(Uri.parse(repo.address));
|
||||
intent.putExtra(Downloader.EXTRA_ERROR_MESSAGE, e.getLocalizedMessage());
|
||||
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
|
||||
})
|
||||
.subscribe()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is for setting things up for when the {@code SwapService} was
|
||||
* started by the user clicking on the initial start button. The things
|
||||
* that must be run always on start-up go in {@link #onCreate()}.
|
||||
*/
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
deleteAllSwapRepos();
|
||||
Intent startUiIntent = new Intent(this, SwapWorkflowActivity.class);
|
||||
startUiIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
startActivity(startUiIntent);
|
||||
return START_NOT_STICKY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
// reset the timer on each new connect, the user has come back
|
||||
initTimer();
|
||||
return binder;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
compositeDisposable.dispose();
|
||||
|
||||
Utils.debugLog(TAG, "Destroying service, will disable swapping if required, and unregister listeners.");
|
||||
Preferences.get().unregisterLocalRepoHttpsListeners(httpsEnabledListener);
|
||||
localBroadcastManager.unregisterReceiver(onWifiChange);
|
||||
localBroadcastManager.unregisterReceiver(bluetoothStatus);
|
||||
localBroadcastManager.unregisterReceiver(bluetoothPeerFound);
|
||||
localBroadcastManager.unregisterReceiver(bonjourPeerFound);
|
||||
localBroadcastManager.unregisterReceiver(bonjourPeerRemoved);
|
||||
|
||||
if (bluetoothAdapter != null) {
|
||||
unregisterReceiver(bluetoothScanModeChanged);
|
||||
}
|
||||
|
||||
BluetoothManager.stop(this);
|
||||
|
||||
BonjourManager.stop(this);
|
||||
LocalHTTPDManager.stop(this);
|
||||
if (wifiManager != null && !wasWifiEnabledBeforeSwap()) {
|
||||
wifiManager.setWifiEnabled(false);
|
||||
}
|
||||
|
||||
WifiApControl ap = WifiApControl.getInstance(this);
|
||||
if (ap != null) {
|
||||
if (wasHotspotEnabledBeforeSwap()) {
|
||||
ap.enable();
|
||||
} else {
|
||||
ap.disable();
|
||||
}
|
||||
}
|
||||
|
||||
stopPollingConnectedSwapRepo();
|
||||
|
||||
if (timer != null) {
|
||||
timer.cancel();
|
||||
}
|
||||
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE);
|
||||
|
||||
deleteAllSwapRepos();
|
||||
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
private Notification createNotification() {
|
||||
Intent intent = new Intent(this, SwapWorkflowActivity.class);
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
|
||||
return new NotificationCompat.Builder(this, NotificationHelper.CHANNEL_SWAPS)
|
||||
.setContentTitle(getText(R.string.local_repo_running))
|
||||
.setContentText(getText(R.string.touch_to_configure_local_repo))
|
||||
.setSmallIcon(R.drawable.ic_nearby)
|
||||
.setContentIntent(contentIntent)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* For now, swap repos are only trusted as long as swapping is active. They
|
||||
* should have a long lived trust based on the signing key, but that requires
|
||||
* that the repos are stored in the database by fingerprint, not by URL address.
|
||||
*
|
||||
* @see <a href="https://gitlab.com/fdroid/fdroidclient/issues/295">TOFU in swap</a>
|
||||
* @see <a href="https://gitlab.com/fdroid/fdroidclient/issues/703">
|
||||
* signing key fingerprint should be sole ID for repos in the database</a>
|
||||
*/
|
||||
private void deleteAllSwapRepos() {
|
||||
for (Repo repo : RepoProvider.Helper.all(this)) {
|
||||
if (repo.isSwap) {
|
||||
Utils.debugLog(TAG, "Removing stale swap repo: " + repo.address + " - " + repo.fingerprint);
|
||||
RepoProvider.Helper.remove(this, repo.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startPollingConnectedSwapRepo() {
|
||||
stopPollingConnectedSwapRepo();
|
||||
pollConnectedSwapRepoTimer = new Timer("pollConnectedSwapRepoTimer", true);
|
||||
TimerTask timerTask = new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (peer != null) {
|
||||
connectTo(peer);
|
||||
}
|
||||
}
|
||||
};
|
||||
pollConnectedSwapRepoTimer.schedule(timerTask, 5000);
|
||||
}
|
||||
|
||||
public void stopPollingConnectedSwapRepo() {
|
||||
if (pollConnectedSwapRepoTimer != null) {
|
||||
pollConnectedSwapRepoTimer.cancel();
|
||||
pollConnectedSwapRepoTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets or resets the idel timer for {@link #TIMEOUT}ms, once the timer
|
||||
* expires, this service and all things that rely on it will be stopped.
|
||||
*/
|
||||
public void initTimer() {
|
||||
if (timer != null) {
|
||||
Utils.debugLog(TAG, "Cancelling existing timeout timer so timeout can be reset.");
|
||||
timer.cancel();
|
||||
}
|
||||
|
||||
Utils.debugLog(TAG, "Initializing swap timeout to " + TIMEOUT + "ms minutes");
|
||||
timer = new Timer(TAG, true);
|
||||
timer.schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
Utils.debugLog(TAG, "Disabling swap because " + TIMEOUT + "ms passed.");
|
||||
String msg = getString(R.string.swap_toast_closing_nearby_after_timeout);
|
||||
Utils.showToastFromService(SwapService.this, msg, android.widget.Toast.LENGTH_LONG);
|
||||
stop(SwapService.this);
|
||||
}
|
||||
}, TIMEOUT);
|
||||
}
|
||||
|
||||
private void restartWiFiServices() {
|
||||
boolean hasIp = FDroidApp.ipAddressString != null;
|
||||
if (hasIp) {
|
||||
LocalHTTPDManager.restart(this);
|
||||
BonjourManager.restart(this);
|
||||
BonjourManager.setVisible(this, getWifiVisibleUserPreference() || getHotspotActivatedUserPreference());
|
||||
} else {
|
||||
BonjourManager.stop(this);
|
||||
LocalHTTPDManager.stop(this);
|
||||
}
|
||||
}
|
||||
|
||||
private final Preferences.ChangeListener httpsEnabledListener = new Preferences.ChangeListener() {
|
||||
@Override
|
||||
public void onPreferenceChange() {
|
||||
restartWiFiServices();
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver onWifiChange = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent i) {
|
||||
restartWiFiServices();
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver bluetoothStatus = new SwapStateChangeReceiver();
|
||||
private final BroadcastReceiver localRepoStatus = new SwapStateChangeReceiver();
|
||||
|
||||
/**
|
||||
* When swapping is setup, then start the index polling.
|
||||
*/
|
||||
private class SwapStateChangeReceiver extends BroadcastReceiver {
|
||||
private final BroadcastReceiver pollForUpdatesReceiver = new PollForUpdatesReceiver();
|
||||
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
int bluetoothStatus = intent.getIntExtra(BluetoothManager.ACTION_STATUS, -1);
|
||||
int wifiStatus = intent.getIntExtra(LocalRepoService.EXTRA_STATUS, -1);
|
||||
if (bluetoothStatus == BluetoothManager.STATUS_STARTED
|
||||
|| wifiStatus == LocalRepoService.STATUS_STARTED) {
|
||||
localBroadcastManager.registerReceiver(pollForUpdatesReceiver,
|
||||
new IntentFilter(UpdateService.LOCAL_ACTION_STATUS));
|
||||
} else {
|
||||
localBroadcastManager.unregisterReceiver(pollForUpdatesReceiver);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reschedule an index update if the last one was successful.
|
||||
*/
|
||||
private class PollForUpdatesReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
switch (intent.getIntExtra(UpdateService.EXTRA_STATUS_CODE, -1)) {
|
||||
case UpdateService.STATUS_COMPLETE_AND_SAME:
|
||||
case UpdateService.STATUS_COMPLETE_WITH_CHANGES:
|
||||
startPollingConnectedSwapRepo();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle events if the user or system changes the Bluetooth setup outside of F-Droid.
|
||||
*/
|
||||
private final BroadcastReceiver bluetoothScanModeChanged = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
switch (intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, -1)) {
|
||||
case BluetoothAdapter.SCAN_MODE_NONE:
|
||||
BluetoothManager.stop(SwapService.this);
|
||||
break;
|
||||
|
||||
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
|
||||
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
|
||||
BluetoothManager.start(SwapService.this);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver bluetoothPeerFound = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
activePeers.add((Peer) intent.getParcelableExtra(BluetoothManager.EXTRA_PEER));
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver bonjourPeerFound = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
activePeers.add((Peer) intent.getParcelableExtra(BonjourManager.EXTRA_BONJOUR_PEER));
|
||||
}
|
||||
};
|
||||
|
||||
private final BroadcastReceiver bonjourPeerRemoved = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
activePeers.remove((Peer) intent.getParcelableExtra(BonjourManager.EXTRA_BONJOUR_PEER));
|
||||
}
|
||||
};
|
||||
}
|
@ -1,93 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.content.res.TypedArray;
|
||||
import android.util.AttributeSet;
|
||||
import android.widget.RelativeLayout;
|
||||
|
||||
import org.fdroid.fdroid.R;
|
||||
|
||||
import androidx.annotation.ColorInt;
|
||||
import androidx.annotation.LayoutRes;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
/**
|
||||
* A {@link android.view.View} that registers to handle the swap events from
|
||||
* {@link SwapService}.
|
||||
*/
|
||||
public class SwapView extends RelativeLayout {
|
||||
public static final String TAG = "SwapView";
|
||||
|
||||
@ColorInt
|
||||
public final int toolbarColor;
|
||||
public final String toolbarTitle;
|
||||
|
||||
private int layoutResId = -1;
|
||||
|
||||
protected String currentFilterString;
|
||||
|
||||
public SwapView(Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public SwapView(Context context, AttributeSet attrs) {
|
||||
this(context, attrs, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* In order to support Android < 21, this calls {@code super} rather than
|
||||
* {@code this}. {@link RelativeLayout}'s methods just use a 0 for the
|
||||
* fourth argument, just like this used to.
|
||||
*/
|
||||
public SwapView(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
final TypedArray a = context.obtainStyledAttributes(
|
||||
attrs, R.styleable.SwapView, 0, 0);
|
||||
toolbarColor = a.getColor(R.styleable.SwapView_toolbarColor,
|
||||
ContextCompat.getColor(context, R.color.swap_blue));
|
||||
toolbarTitle = a.getString(R.styleable.SwapView_toolbarTitle);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
@TargetApi(21)
|
||||
public SwapView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
final TypedArray a = context.obtainStyledAttributes(
|
||||
attrs, R.styleable.SwapView, 0, 0);
|
||||
toolbarColor = a.getColor(R.styleable.SwapView_toolbarColor,
|
||||
ContextCompat.getColor(context, R.color.swap_blue));
|
||||
toolbarTitle = a.getString(R.styleable.SwapView_toolbarTitle);
|
||||
a.recycle();
|
||||
}
|
||||
|
||||
@LayoutRes
|
||||
public int getLayoutResId() {
|
||||
return layoutResId;
|
||||
}
|
||||
|
||||
public void setLayoutResId(@LayoutRes int layoutResId) {
|
||||
this.layoutResId = layoutResId;
|
||||
}
|
||||
|
||||
public String getCurrentFilterString() {
|
||||
return this.currentFilterString;
|
||||
}
|
||||
|
||||
public void setCurrentFilterString(String currentFilterString) {
|
||||
this.currentFilterString = currentFilterString;
|
||||
}
|
||||
|
||||
public SwapWorkflowActivity getActivity() {
|
||||
return (SwapWorkflowActivity) getContext();
|
||||
}
|
||||
|
||||
@ColorInt
|
||||
public int getToolbarColour() {
|
||||
return toolbarColor;
|
||||
}
|
||||
|
||||
public String getToolbarTitle() {
|
||||
return toolbarTitle;
|
||||
}
|
||||
}
|
@ -1,210 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.IntentService;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Process;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.fdroid.fdroid.AddRepoIntentService;
|
||||
import org.fdroid.fdroid.IndexUpdater;
|
||||
import org.fdroid.fdroid.IndexV1Updater;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.data.Repo;
|
||||
import org.fdroid.fdroid.data.RepoProvider;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.cert.Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.jar.JarInputStream;
|
||||
|
||||
import androidx.documentfile.provider.DocumentFile;
|
||||
|
||||
/**
|
||||
* An {@link IntentService} subclass for handling asynchronous scanning of a
|
||||
* removable storage device like an SD Card or USB OTG thumb drive using the
|
||||
* Storage Access Framework. Permission must first be granted by the user
|
||||
* {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or
|
||||
* {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,
|
||||
* then F-Droid will have permanent access to that{@link Uri}.
|
||||
* <p>
|
||||
* Even though the Storage Access Framework was introduced in
|
||||
* {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only
|
||||
* workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.
|
||||
* It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.
|
||||
* {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also
|
||||
* necessary to do this with any kind of rational UX.
|
||||
*
|
||||
* @see <a href="https://commonsware.com/blog/2017/11/15/storage-situation-removable-storage.html">The Storage Situation: Removable Storage </a>
|
||||
* @see <a href="https://commonsware.com/blog/2016/11/18/be-careful-scoped-directory-access.html">Be Careful with Scoped Directory Access</a>
|
||||
* @see <a href="https://developer.android.com/training/articles/scoped-directory-access.html">Using Scoped Directory Access</a>
|
||||
* @see <a href="https://developer.android.com/guide/topics/providers/document-provider.html">Open Files using Storage Access Framework</a>
|
||||
*/
|
||||
@TargetApi(21)
|
||||
public class TreeUriScannerIntentService extends IntentService {
|
||||
public static final String TAG = "TreeUriScannerIntentSer";
|
||||
|
||||
private static final String ACTION_SCAN_TREE_URI = "org.fdroid.fdroid.nearby.action.SCAN_TREE_URI";
|
||||
/**
|
||||
* @see <a href="https://android.googlesource.com/platform/frameworks/base/+/android-10.0.0_r38/core/java/android/provider/DocumentsContract.java#238">DocumentsContract.EXTERNAL_STORAGE_PROVIDER_AUTHORITY</a>
|
||||
* @see <a href="https://android.googlesource.com/platform/frameworks/base/+/android-10.0.0_r38/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java#70">ExternalStorageProvider.AUTHORITY</a>
|
||||
*/
|
||||
public static final String EXTERNAL_STORAGE_PROVIDER_AUTHORITY = "com.android.externalstorage.documents";
|
||||
|
||||
public TreeUriScannerIntentService() {
|
||||
super("TreeUriScannerIntentService");
|
||||
}
|
||||
|
||||
public static void scan(Context context, Uri data) {
|
||||
Intent intent = new Intent(context, TreeUriScannerIntentService.class);
|
||||
intent.setAction(ACTION_SCAN_TREE_URI);
|
||||
intent.setData(data);
|
||||
context.startService(intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Now determine if it is External Storage that must be handled by the
|
||||
* {@link TreeUriScannerIntentService} or whether it is External Storage
|
||||
* like an SD Card that can be directly accessed via the file system.
|
||||
*/
|
||||
public static void onActivityResult(Context context, Intent intent) {
|
||||
if (intent == null) {
|
||||
return;
|
||||
}
|
||||
Uri uri = intent.getData();
|
||||
if (uri != null) {
|
||||
if (Build.VERSION.SDK_INT >= 19) {
|
||||
ContentResolver contentResolver = context.getContentResolver();
|
||||
int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
|
||||
contentResolver.takePersistableUriPermission(uri, perms);
|
||||
}
|
||||
String msg = String.format(context.getString(R.string.swap_toast_using_path), uri.toString());
|
||||
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
|
||||
scan(context, uri);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onHandleIntent(Intent intent) {
|
||||
if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {
|
||||
return;
|
||||
}
|
||||
Uri treeUri = intent.getData();
|
||||
if (treeUri == null) {
|
||||
return;
|
||||
}
|
||||
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
|
||||
DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);
|
||||
searchDirectory(treeFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting
|
||||
* from the given directory, looking at files first before recursing into
|
||||
* directories. This is "depth last" since the index file is much more
|
||||
* likely to be shallow than deep, and there can be a lot of files to
|
||||
* search through starting at 4 or more levels deep, like the fdroid
|
||||
* icons dirs and the per-app "external storage" dirs.
|
||||
*/
|
||||
private void searchDirectory(DocumentFile documentFileDir) {
|
||||
DocumentFile[] documentFiles = documentFileDir.listFiles();
|
||||
if (documentFiles == null) {
|
||||
return;
|
||||
}
|
||||
boolean foundIndex = false;
|
||||
ArrayList<DocumentFile> dirs = new ArrayList<>();
|
||||
for (DocumentFile documentFile : documentFiles) {
|
||||
if (documentFile.isDirectory()) {
|
||||
dirs.add(documentFile);
|
||||
} else if (!foundIndex) {
|
||||
if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {
|
||||
registerRepo(documentFile);
|
||||
foundIndex = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (DocumentFile dir : dirs) {
|
||||
searchDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check
|
||||
* the JAR signature and read the fingerprint of the signing certificate.
|
||||
* The fingerprint is then used to find whether this local repo is a mirror
|
||||
* of an existing repo, or a totally new repo. In order to verify the
|
||||
* signatures in the JAR, the whole file needs to be read in first.
|
||||
*
|
||||
* @see JarInputStream#JarInputStream(InputStream, boolean)
|
||||
*/
|
||||
private void registerRepo(DocumentFile index) {
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
inputStream = getContentResolver().openInputStream(index.getUri());
|
||||
registerRepo(this, inputStream, index.getParentFile().getUri());
|
||||
} catch (IOException | IndexUpdater.SigningException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
Utils.closeQuietly(inputStream);
|
||||
}
|
||||
}
|
||||
|
||||
public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)
|
||||
throws IOException, IndexUpdater.SigningException {
|
||||
if (inputStream == null) {
|
||||
return;
|
||||
}
|
||||
File destFile = File.createTempFile("dl-", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());
|
||||
FileUtils.copyInputStreamToFile(inputStream, destFile);
|
||||
JarFile jarFile = new JarFile(destFile, true);
|
||||
JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);
|
||||
IOUtils.readLines(jarFile.getInputStream(indexEntry));
|
||||
Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);
|
||||
String fingerprint = Utils.calcFingerprint(certificate);
|
||||
Log.i(TAG, "Got fingerprint: " + fingerprint);
|
||||
destFile.delete();
|
||||
|
||||
Log.i(TAG, "Found a valid, signed index-v1.json");
|
||||
for (Repo repo : RepoProvider.Helper.all(context)) {
|
||||
if (fingerprint.equals(repo.fingerprint)) {
|
||||
Log.i(TAG, repo.address + " has the SAME fingerprint: " + fingerprint);
|
||||
} else {
|
||||
Log.i(TAG, repo.address + " different fingerprint");
|
||||
}
|
||||
}
|
||||
|
||||
AddRepoIntentService.addRepo(context, repoUri, fingerprint);
|
||||
// TODO rework IndexUpdater.getSigningCertFromJar to work for here
|
||||
}
|
||||
}
|
@ -1,97 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.annotation.TargetApi;
|
||||
import android.content.Context;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.storage.StorageManager;
|
||||
import android.provider.DocumentsContract;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
|
||||
/**
|
||||
* @see <a href="https://stackoverflow.com/a/36162691">Android 5.0 DocumentFile from tree URI</a>
|
||||
*/
|
||||
public final class TreeUriUtils {
|
||||
public static final String TAG = "TreeUriUtils";
|
||||
|
||||
private static final String PRIMARY_VOLUME_NAME = "primary";
|
||||
|
||||
@Nullable
|
||||
public static String getFullPathFromTreeUri(Context context, @Nullable final Uri treeUri) {
|
||||
if (treeUri == null) return null;
|
||||
String volumePath = getVolumePath(getVolumeIdFromTreeUri(treeUri), context);
|
||||
if (volumePath == null) return File.separator;
|
||||
if (volumePath.endsWith(File.separator))
|
||||
volumePath = volumePath.substring(0, volumePath.length() - 1);
|
||||
|
||||
String documentPath = getDocumentPathFromTreeUri(treeUri);
|
||||
if (documentPath.endsWith(File.separator))
|
||||
documentPath = documentPath.substring(0, documentPath.length() - 1);
|
||||
|
||||
if (documentPath.length() > 0) {
|
||||
if (documentPath.startsWith(File.separator))
|
||||
return volumePath + documentPath;
|
||||
else
|
||||
return volumePath + File.separator + documentPath;
|
||||
} else return volumePath;
|
||||
}
|
||||
|
||||
|
||||
@SuppressLint("ObsoleteSdkInt")
|
||||
private static String getVolumePath(final String volumeId, Context context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null;
|
||||
try {
|
||||
StorageManager mStorageManager = ContextCompat.getSystemService(context, StorageManager.class);
|
||||
Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
|
||||
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
|
||||
Method getUuid = storageVolumeClazz.getMethod("getUuid");
|
||||
Method getPath = storageVolumeClazz.getMethod("getPath");
|
||||
Method isPrimary = storageVolumeClazz.getMethod("isPrimary");
|
||||
Object result = getVolumeList.invoke(mStorageManager);
|
||||
|
||||
final int length = Array.getLength(result);
|
||||
for (int i = 0; i < length; i++) {
|
||||
Object storageVolumeElement = Array.get(result, i);
|
||||
String uuid = (String) getUuid.invoke(storageVolumeElement);
|
||||
Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement);
|
||||
|
||||
// primary volume?
|
||||
if (primary && PRIMARY_VOLUME_NAME.equals(volumeId))
|
||||
return (String) getPath.invoke(storageVolumeElement);
|
||||
|
||||
// other volumes?
|
||||
if (uuid != null && uuid.equals(volumeId))
|
||||
return (String) getPath.invoke(storageVolumeElement);
|
||||
}
|
||||
// not found.
|
||||
return null;
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private static String getVolumeIdFromTreeUri(final Uri treeUri) {
|
||||
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
|
||||
final String[] split = docId.split(":");
|
||||
if (split.length > 0) return split[0];
|
||||
else return null;
|
||||
}
|
||||
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
|
||||
private static String getDocumentPathFromTreeUri(final Uri treeUri) {
|
||||
final String docId = DocumentsContract.getTreeDocumentId(treeUri);
|
||||
final String[] split = docId.split(":");
|
||||
if ((split.length >= 2) && (split[1] != null)) return split[1];
|
||||
else return File.separator;
|
||||
}
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2019 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.UriPermission;
|
||||
import android.database.ContentObserver;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.views.main.NearbyViewBinder;
|
||||
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
|
||||
/**
|
||||
* This is just a shim to receive {@link UsbManager#ACTION_USB_ACCESSORY_ATTACHED}
|
||||
* events.
|
||||
*/
|
||||
public class UsbDeviceAttachedReceiver extends BroadcastReceiver {
|
||||
public static final String TAG = "UsbDeviceAttachedReceiv";
|
||||
|
||||
|
||||
@RequiresApi(api = 19)
|
||||
@Override
|
||||
public void onReceive(final Context context, Intent intent) {
|
||||
if (Build.VERSION.SDK_INT < 19) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (intent == null || TextUtils.isEmpty(intent.getAction())
|
||||
|| !UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
|
||||
Log.i(TAG, "ignoring irrelevant intent: " + intent);
|
||||
return;
|
||||
}
|
||||
Log.i(TAG, "handling intent: " + intent);
|
||||
|
||||
final ContentResolver contentResolver = context.getContentResolver();
|
||||
|
||||
for (final UriPermission uriPermission : contentResolver.getPersistedUriPermissions()) {
|
||||
Uri uri = uriPermission.getUri();
|
||||
final ContentObserver contentObserver = new ContentObserver(new Handler()) {
|
||||
|
||||
@Override
|
||||
public void onChange(boolean selfChange, Uri uri) {
|
||||
NearbyViewBinder.updateUsbOtg(context);
|
||||
}
|
||||
};
|
||||
contentResolver.registerContentObserver(uri, true, contentObserver);
|
||||
UsbDeviceDetachedReceiver.contentObservers.put(uri, contentObserver);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2018-2019 Hans-Christoph Steiner <hans@eds.org>
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
||||
* MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.database.ContentObserver;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.views.main.NearbyViewBinder;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
/**
|
||||
* This is just a shim to receive {@link UsbManager#ACTION_USB_DEVICE_DETACHED}
|
||||
* events.
|
||||
*/
|
||||
public class UsbDeviceDetachedReceiver extends BroadcastReceiver {
|
||||
public static final String TAG = "UsbDeviceDetachedReceiv";
|
||||
|
||||
static final HashMap<Uri, ContentObserver> contentObservers = new HashMap<>();
|
||||
|
||||
@RequiresApi(api = 19)
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (Build.VERSION.SDK_INT < 19) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (intent == null || TextUtils.isEmpty(intent.getAction())
|
||||
|| !UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
|
||||
Log.i(TAG, "ignoring irrelevant intent: " + intent);
|
||||
return;
|
||||
}
|
||||
Log.i(TAG, "handling intent: " + intent);
|
||||
|
||||
final ContentResolver contentResolver = context.getContentResolver();
|
||||
NearbyViewBinder.updateUsbOtg(context);
|
||||
for (ContentObserver contentObserver : contentObservers.values()) {
|
||||
contentResolver.unregisterContentObserver(contentObserver);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Environment;
|
||||
|
||||
import org.fdroid.fdroid.views.main.NearbyViewBinder;
|
||||
|
||||
public class UsbDeviceMediaMountedReceiver extends BroadcastReceiver {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
if (intent == null || intent.getAction() == null) {
|
||||
return;
|
||||
}
|
||||
String action = intent.getAction();
|
||||
if (Environment.MEDIA_BAD_REMOVAL.equals(action)
|
||||
|| Environment.MEDIA_MOUNTED.equals(action)
|
||||
|| Environment.MEDIA_REMOVED.equals(action)
|
||||
|| Environment.MEDIA_EJECTING.equals(action)) {
|
||||
NearbyViewBinder.updateUsbOtg(context);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package org.fdroid.fdroid.nearby.peers;
|
||||
|
||||
import android.os.Parcelable;
|
||||
|
||||
import androidx.annotation.DrawableRes;
|
||||
|
||||
/**
|
||||
* TODO This model assumes that "peers" from Bluetooth, Bonjour, and WiFi are
|
||||
* different things. They are not different repos though, they all point to
|
||||
* the same repos. This should really be combined to be a single "RemoteRepo"
|
||||
* class that represents a single device's local repo, and can have zero to
|
||||
* many ways to connect to it (e.g. Bluetooth, WiFi, USB Thumb Drive, SD Card,
|
||||
* WiFi Direct, etc).
|
||||
*/
|
||||
public interface Peer extends Parcelable {
|
||||
|
||||
String getName();
|
||||
|
||||
@DrawableRes
|
||||
int getIcon();
|
||||
|
||||
boolean equals(Object peer);
|
||||
|
||||
String getRepoAddress();
|
||||
|
||||
String getFingerprint();
|
||||
|
||||
boolean shouldPromptForSwapBack();
|
||||
}
|
@ -1,159 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import com.google.android.material.appbar.MaterialToolbar;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
/**
|
||||
* A very hacky calculator which is barely functional.
|
||||
* It is just meant to pass a very casual inspection.
|
||||
*/
|
||||
public class CalculatorActivity extends AppCompatActivity {
|
||||
|
||||
// binary operators
|
||||
private static final String TIMES = "×";
|
||||
private static final String DIVIDED = "÷";
|
||||
private static final String PLUS = "+";
|
||||
private static final String MINUS = "-";
|
||||
|
||||
// unary operators
|
||||
private static final String PERCENT = "%";
|
||||
|
||||
@Nullable
|
||||
private String lastOp;
|
||||
|
||||
// views
|
||||
private TextView textView;
|
||||
|
||||
@Override
|
||||
protected void onCreate(@Nullable Bundle savedInstanceState) {
|
||||
FDroidApp fdroidApp = (FDroidApp) getApplication();
|
||||
fdroidApp.applyPureBlackBackgroundInDarkTheme(this);
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_calculator);
|
||||
|
||||
MaterialToolbar toolbar = findViewById(R.id.toolbar);
|
||||
setSupportActionBar(toolbar);
|
||||
|
||||
textView = (TextView) findViewById(R.id.textView);
|
||||
}
|
||||
|
||||
public void ce(View view) {
|
||||
// clear display
|
||||
textView.setText(null);
|
||||
}
|
||||
|
||||
public void c(View view) {
|
||||
// clear last character
|
||||
if (textView.length() > 0) {
|
||||
String text = textView.getText().toString();
|
||||
textView.setText(text.substring(0, text.length() - 1));
|
||||
}
|
||||
}
|
||||
|
||||
public void number(View view) {
|
||||
String number = ((Button) view).getText().toString();
|
||||
String newNumber = String.format("%s%s", textView.getText(), number);
|
||||
// FIXME don't allow multiple commas
|
||||
String pin = String.valueOf(HidingManager.getUnhidePin(this));
|
||||
if (newNumber.equals(pin)) {
|
||||
// correct PIN was entered, show app launcher again
|
||||
HidingManager.show(this);
|
||||
}
|
||||
textView.setText(newNumber);
|
||||
}
|
||||
|
||||
public void op(View view) {
|
||||
String text = textView.getText().toString();
|
||||
|
||||
if (text.length() == 0) {
|
||||
return;
|
||||
} else if (containsBinaryOperator(String.valueOf(text.charAt(text.length() - 1)))) {
|
||||
// last character was already binary operator, ignore
|
||||
return;
|
||||
}
|
||||
|
||||
String op = ((Button) view).getText().toString();
|
||||
if (containsBinaryOperator(op)) {
|
||||
// remember binary operator
|
||||
lastOp = op;
|
||||
// add binary operator to display
|
||||
textView.setText(String.format("%s%s", text, op));
|
||||
} else if (op.equals(PERCENT)) {
|
||||
double result;
|
||||
try {
|
||||
result = Double.valueOf(eval(text));
|
||||
} catch (NumberFormatException e) {
|
||||
result = 0;
|
||||
}
|
||||
textView.setText(toString(result / 100));
|
||||
} else if ("=".equals(op)) {
|
||||
textView.setText(eval(text));
|
||||
} else {
|
||||
Toast.makeText(this, "Error: Unknown Operation", Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
private String eval(String s) {
|
||||
if (lastOp != null && s.contains(lastOp)) {
|
||||
// remember and reset binary operator
|
||||
String op = lastOp;
|
||||
lastOp = null;
|
||||
|
||||
// extract binary operation
|
||||
String[] parts = s.split(Pattern.quote(op));
|
||||
double left;
|
||||
double right;
|
||||
try {
|
||||
left = Double.valueOf(parts[0]);
|
||||
right = Double.valueOf(parts[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// evaluate binary operation
|
||||
switch (op) {
|
||||
case PLUS:
|
||||
return toString(left + right);
|
||||
case MINUS:
|
||||
return toString(left - right);
|
||||
case TIMES:
|
||||
return toString(left * right);
|
||||
case DIVIDED:
|
||||
if (right == 0) return "";
|
||||
return toString(left / right);
|
||||
default:
|
||||
Toast.makeText(this, "Error: Unknown Operation", Toast.LENGTH_SHORT).show();
|
||||
return s;
|
||||
}
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean containsBinaryOperator(String s) {
|
||||
return s.contains(TIMES) || s.contains(DIVIDED) || s.contains(PLUS) || s.contains(MINUS);
|
||||
}
|
||||
|
||||
private String toString(double d) {
|
||||
String s = String.valueOf(d);
|
||||
if (s.length() > 2 && s.endsWith(".0")) {
|
||||
return s.substring(0, s.length() - 2);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.preference.CheckBoxPreference;
|
||||
import androidx.preference.PreferenceViewHolder;
|
||||
|
||||
public class DestructiveCheckBoxPreference extends CheckBoxPreference {
|
||||
public DestructiveCheckBoxPreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
public DestructiveCheckBoxPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
public DestructiveCheckBoxPreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public DestructiveCheckBoxPreference(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(PreferenceViewHolder holder) {
|
||||
super.onBindViewHolder(holder);
|
||||
if (!holder.itemView.isEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (FDroidApp.isAppThemeLight()) {
|
||||
holder.itemView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.panic_destructive_light));
|
||||
} else {
|
||||
holder.itemView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.panic_destructive_dark));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.preference.Preference;
|
||||
import androidx.preference.PreferenceViewHolder;
|
||||
|
||||
public class DestructivePreference extends Preference {
|
||||
public DestructivePreference(Context context, AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
}
|
||||
|
||||
public DestructivePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
}
|
||||
|
||||
public DestructivePreference(Context context, AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public DestructivePreference(Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(PreferenceViewHolder holder) {
|
||||
super.onBindViewHolder(holder);
|
||||
if (FDroidApp.isAppThemeLight()) {
|
||||
holder.itemView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.panic_destructive_light));
|
||||
} else {
|
||||
holder.itemView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.panic_destructive_dark));
|
||||
}
|
||||
}
|
||||
}
|
@ -1,41 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class ExitActivity extends AppCompatActivity {
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 21) {
|
||||
finishAndRemoveTask();
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
public static void exitAndRemoveFromRecentApps(final AppCompatActivity activity) {
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Intent intent = new Intent(activity, ExitActivity.class);
|
||||
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
|
||||
| Intent.FLAG_ACTIVITY_CLEAR_TASK
|
||||
| Intent.FLAG_ACTIVITY_NO_ANIMATION);
|
||||
|
||||
activity.startActivity(intent);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ServiceInfo;
|
||||
|
||||
import org.fdroid.fdroid.BuildConfig;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.views.main.MainActivity;
|
||||
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
|
||||
/**
|
||||
* This class is encapsulating all methods related to hiding the app from the launcher
|
||||
* and restoring it.
|
||||
* <p>
|
||||
* It can tell you whether the app is hidden, what the PIN to restore is
|
||||
* and show confirmation dialogs before hiding.
|
||||
*/
|
||||
public class HidingManager {
|
||||
|
||||
private static final ComponentName LAUNCHER_NAME =
|
||||
new ComponentName(BuildConfig.APPLICATION_ID, MainActivity.class.getName());
|
||||
|
||||
private static final ComponentName CALCULATOR_NAME =
|
||||
new ComponentName(BuildConfig.APPLICATION_ID, CalculatorActivity.class.getName());
|
||||
|
||||
public static int getUnhidePin(Context context) {
|
||||
return context.getResources().getInteger(R.integer.unhidePin);
|
||||
}
|
||||
|
||||
public static boolean isHidden(Context context) {
|
||||
PackageManager pm = context.getPackageManager();
|
||||
int state = pm.getComponentEnabledSetting(LAUNCHER_NAME);
|
||||
return state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
|
||||
}
|
||||
|
||||
public static void showHideDialog(final Context context) {
|
||||
String appName = context.getString(R.string.app_name);
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(context);
|
||||
builder.setTitle(context.getString(R.string.hiding_dialog_title, appName));
|
||||
builder.setMessage(context.getString(R.string.hiding_dialog_message, appName,
|
||||
HidingManager.getUnhidePin(context), context.getString(R.string.hiding_calculator)));
|
||||
builder.setPositiveButton(context.getString(R.string.panic_hide_title, appName),
|
||||
new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
hide(context);
|
||||
}
|
||||
});
|
||||
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
dialogInterface.cancel();
|
||||
}
|
||||
});
|
||||
builder.setView(R.layout.dialog_app_hiding);
|
||||
builder.create().show();
|
||||
}
|
||||
|
||||
public static void hide(Context context) {
|
||||
stopServices(context);
|
||||
removeNotifications(context);
|
||||
|
||||
PackageManager pm = context.getPackageManager();
|
||||
// hide launcher icon
|
||||
pm.setComponentEnabledSetting(LAUNCHER_NAME,
|
||||
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
|
||||
PackageManager.DONT_KILL_APP);
|
||||
// show calculator icon
|
||||
pm.setComponentEnabledSetting(CALCULATOR_NAME,
|
||||
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
|
||||
0); // please kill app (faster and safer, because it also stops services)
|
||||
}
|
||||
|
||||
public static void show(Context context) {
|
||||
PackageManager pm = context.getPackageManager();
|
||||
// show launcher icon
|
||||
pm.setComponentEnabledSetting(LAUNCHER_NAME,
|
||||
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
|
||||
PackageManager.DONT_KILL_APP);
|
||||
// hide calculator icon
|
||||
pm.setComponentEnabledSetting(CALCULATOR_NAME,
|
||||
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
|
||||
0); // please kill app (faster)
|
||||
}
|
||||
|
||||
private static void removeNotifications(Context context) {
|
||||
NotificationManagerCompat nm = NotificationManagerCompat.from(context);
|
||||
nm.cancelAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops all running services, so nothing can pop up and reveal F-Droid's existence on the system
|
||||
*/
|
||||
private static void stopServices(Context context) {
|
||||
try {
|
||||
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
|
||||
PackageManager.GET_SERVICES);
|
||||
for (ServiceInfo serviceInfo : packageInfo.services) {
|
||||
Intent intent = new Intent();
|
||||
intent.setComponent(new ComponentName(context, serviceInfo.name));
|
||||
context.stopService(intent);
|
||||
}
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
|
||||
import com.google.android.material.appbar.MaterialToolbar;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.R;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class PanicPreferencesActivity extends AppCompatActivity {
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle bundle) {
|
||||
FDroidApp fdroidApp = (FDroidApp) getApplication();
|
||||
fdroidApp.applyPureBlackBackgroundInDarkTheme(this);
|
||||
|
||||
super.onCreate(bundle);
|
||||
setContentView(R.layout.activity_panic_settings);
|
||||
|
||||
MaterialToolbar toolbar = findViewById(R.id.toolbar);
|
||||
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
// Handle navigation icon press
|
||||
onBackPressed();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
@ -1,310 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.ComponentName;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.ResolveInfo;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.LightingColorFilter;
|
||||
import android.graphics.PorterDuff;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.text.TextUtils;
|
||||
import android.util.TypedValue;
|
||||
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.installer.PrivilegedInstaller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
|
||||
import androidx.annotation.ColorInt;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.preference.CheckBoxPreference;
|
||||
import androidx.preference.ListPreference;
|
||||
import androidx.preference.Preference;
|
||||
import androidx.preference.PreferenceCategory;
|
||||
import androidx.preference.PreferenceFragmentCompat;
|
||||
import info.guardianproject.panic.Panic;
|
||||
import info.guardianproject.panic.PanicResponder;
|
||||
|
||||
public class PanicPreferencesFragment extends PreferenceFragmentCompat
|
||||
implements SharedPreferences.OnSharedPreferenceChangeListener {
|
||||
|
||||
private static final String PREF_APP = "pref_panic_app";
|
||||
|
||||
private PackageManager pm;
|
||||
private ListPreference prefApp;
|
||||
private CheckBoxPreference prefExit;
|
||||
private CheckBoxPreference prefHide;
|
||||
private CheckBoxPreference prefResetRepos;
|
||||
private PreferenceCategory categoryAppsToUninstall;
|
||||
|
||||
@Override
|
||||
public void onCreatePreferences(Bundle bundle, String s) {
|
||||
addPreferencesFromResource(R.xml.preferences_panic);
|
||||
|
||||
pm = getActivity().getPackageManager();
|
||||
prefExit = (CheckBoxPreference) findPreference(Preferences.PREF_PANIC_EXIT);
|
||||
prefApp = (ListPreference) findPreference(PREF_APP);
|
||||
prefHide = (CheckBoxPreference) findPreference(Preferences.PREF_PANIC_HIDE);
|
||||
prefHide.setTitle(getString(R.string.panic_hide_title, getString(R.string.app_name)));
|
||||
prefResetRepos = (CheckBoxPreference) findPreference(Preferences.PREF_PANIC_RESET_REPOS);
|
||||
categoryAppsToUninstall = (PreferenceCategory) findPreference("pref_panic_apps_to_uninstall");
|
||||
|
||||
if (PanicResponder.checkForDisconnectIntent(getActivity())) {
|
||||
// the necessary action should have been performed by the check already
|
||||
getActivity().finish();
|
||||
return;
|
||||
}
|
||||
String connectIntentSender = PanicResponder.getConnectIntentSender(getActivity());
|
||||
// if there's a connecting app and it is not the old one
|
||||
if (!TextUtils.isEmpty(connectIntentSender) && !TextUtils.equals(connectIntentSender, PanicResponder
|
||||
.getTriggerPackageName(getActivity()))) {
|
||||
// Show dialog allowing the user to opt-in
|
||||
showOptInDialog();
|
||||
}
|
||||
|
||||
prefApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
|
||||
@Override
|
||||
public boolean onPreferenceChange(Preference preference, Object newValue) {
|
||||
String packageName = (String) newValue;
|
||||
PanicResponder.setTriggerPackageName(getActivity(), packageName);
|
||||
if (packageName.equals(Panic.PACKAGE_NAME_NONE)) {
|
||||
prefHide.setChecked(false);
|
||||
prefHide.setEnabled(false);
|
||||
prefResetRepos.setChecked(false);
|
||||
prefResetRepos.setEnabled(false);
|
||||
getActivity().setResult(AppCompatActivity.RESULT_CANCELED);
|
||||
} else {
|
||||
prefHide.setEnabled(true);
|
||||
prefResetRepos.setEnabled(true);
|
||||
}
|
||||
showPanicApp(packageName);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
showPanicApp(PanicResponder.getTriggerPackageName(getActivity()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
|
||||
|
||||
if (!PrivilegedInstaller.isDefault(getActivity())) {
|
||||
getPreferenceScreen().removePreference(categoryAppsToUninstall);
|
||||
return;
|
||||
}
|
||||
showWipeList();
|
||||
}
|
||||
|
||||
private void showWipeList() {
|
||||
Intent intent = new Intent(getActivity(), SelectInstalledAppsActivity.class);
|
||||
intent.setAction(Intent.ACTION_MAIN);
|
||||
Set<String> wipeSet = Preferences.get().getPanicWipeSet();
|
||||
categoryAppsToUninstall.removeAll();
|
||||
if (Panic.PACKAGE_NAME_NONE.equals(prefApp.getValue())) {
|
||||
categoryAppsToUninstall.setEnabled(false);
|
||||
return;
|
||||
}
|
||||
categoryAppsToUninstall.setEnabled(true);
|
||||
if (wipeSet.size() > 0) {
|
||||
for (String packageName : wipeSet) {
|
||||
Preference preference = new DestructivePreference(getActivity());
|
||||
preference.setSingleLineTitle(true);
|
||||
preference.setIntent(intent);
|
||||
categoryAppsToUninstall.addPreference(preference);
|
||||
try {
|
||||
preference.setTitle(pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)));
|
||||
preference.setIcon(pm.getApplicationIcon(packageName));
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
preference.setTitle(packageName);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Preference preference = new Preference(requireActivity());
|
||||
preference.setIntent(intent);
|
||||
Drawable icon = ContextCompat.getDrawable(requireContext(), R.drawable.ic_add_circle_outline);
|
||||
icon.setColorFilter(new LightingColorFilter(0, getResources().getColor(R.color.swap_light_grey_icon)));
|
||||
preference.setSingleLineTitle(true);
|
||||
preference.setTitle(R.string.panic_add_apps_to_uninstall);
|
||||
preference.setIcon(icon);
|
||||
categoryAppsToUninstall.addPreference(preference);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStop() {
|
||||
super.onStop();
|
||||
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
|
||||
if (key.equals(Preferences.PREF_PANIC_HIDE)
|
||||
&& sharedPreferences.getBoolean(Preferences.PREF_PANIC_HIDE, false)) {
|
||||
showHideConfirmationDialog();
|
||||
}
|
||||
// disable "hiding" if "exit" gets disabled
|
||||
if (key.equals(Preferences.PREF_PANIC_EXIT)
|
||||
&& !sharedPreferences.getBoolean(Preferences.PREF_PANIC_EXIT, true)) {
|
||||
prefHide.setChecked(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void showPanicApp(String packageName) {
|
||||
// Fill list of available panic apps
|
||||
ArrayList<CharSequence> entries = new ArrayList<>();
|
||||
ArrayList<CharSequence> entryValues = new ArrayList<>();
|
||||
entries.add(0, getString(R.string.panic_app_setting_none));
|
||||
entryValues.add(0, Panic.PACKAGE_NAME_NONE);
|
||||
|
||||
for (ResolveInfo resolveInfo : PanicResponder.resolveTriggerApps(pm)) {
|
||||
if (resolveInfo.activityInfo == null) continue;
|
||||
entries.add(resolveInfo.activityInfo.loadLabel(pm));
|
||||
entryValues.add(resolveInfo.activityInfo.packageName);
|
||||
}
|
||||
|
||||
prefApp.setEntries(entries.toArray(new CharSequence[entries.size()]));
|
||||
prefApp.setEntryValues(entryValues.toArray(new CharSequence[entryValues.size()]));
|
||||
prefApp.setDefaultValue(Panic.PACKAGE_NAME_NONE);
|
||||
|
||||
if (entries.size() <= 1) {
|
||||
// bring the user to Ripple if no other panic apps are available
|
||||
prefApp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
|
||||
@Override
|
||||
public boolean onPreferenceClick(Preference preference) {
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setData(Uri.parse("market://details?id=info.guardianproject.ripple"));
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
|
||||
startActivity(intent);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (TextUtils.isEmpty(packageName) || packageName.equals(Panic.PACKAGE_NAME_NONE)) {
|
||||
// no panic app set
|
||||
prefApp.setValue(Panic.PACKAGE_NAME_NONE);
|
||||
prefApp.setSummary(getString(R.string.panic_app_setting_summary));
|
||||
|
||||
prefApp.setIcon(null); // otherwise re-setting view resource doesn't work
|
||||
Drawable icon = ContextCompat.getDrawable(getActivity(), R.drawable.ic_cancel);
|
||||
TypedValue typedValue = new TypedValue();
|
||||
Resources.Theme theme = getActivity().getTheme();
|
||||
theme.resolveAttribute(R.attr.appListItem, typedValue, true);
|
||||
@ColorInt int color = typedValue.data;
|
||||
icon.setColorFilter(color, PorterDuff.Mode.SRC_IN);
|
||||
prefApp.setIcon(icon);
|
||||
|
||||
// disable destructive panic actions
|
||||
prefHide.setEnabled(false);
|
||||
showWipeList();
|
||||
} else {
|
||||
// try to display connected panic app
|
||||
try {
|
||||
prefApp.setValue(packageName);
|
||||
prefApp.setSummary(pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)));
|
||||
prefApp.setIcon(pm.getApplicationIcon(packageName));
|
||||
prefHide.setEnabled(true);
|
||||
prefResetRepos.setEnabled(true);
|
||||
showWipeList();
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
// revert back to no app, just to be safe
|
||||
PanicResponder.setTriggerPackageName(getActivity(), Panic.PACKAGE_NAME_NONE);
|
||||
showPanicApp(Panic.PACKAGE_NAME_NONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void showOptInDialog() {
|
||||
DialogInterface.OnClickListener okListener = new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
PanicResponder.setTriggerPackageName(getActivity());
|
||||
showPanicApp(PanicResponder.getTriggerPackageName(getActivity()));
|
||||
getActivity().setResult(AppCompatActivity.RESULT_OK);
|
||||
}
|
||||
};
|
||||
DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
getActivity().setResult(AppCompatActivity.RESULT_CANCELED);
|
||||
getActivity().finish();
|
||||
}
|
||||
};
|
||||
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
|
||||
builder.setTitle(getString(R.string.panic_app_dialog_title));
|
||||
|
||||
CharSequence app = getString(R.string.panic_app_unknown_app);
|
||||
String packageName = getCallingPackageName();
|
||||
if (packageName != null) {
|
||||
try {
|
||||
app = pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0));
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
String text = String.format(getString(R.string.panic_app_dialog_message), app);
|
||||
builder.setMessage(text);
|
||||
builder.setNegativeButton(R.string.allow, okListener);
|
||||
builder.setPositiveButton(R.string.cancel, cancelListener);
|
||||
builder.show();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String getCallingPackageName() {
|
||||
ComponentName componentName = getActivity().getCallingActivity();
|
||||
String packageName = null;
|
||||
if (componentName != null) {
|
||||
packageName = componentName.getPackageName();
|
||||
}
|
||||
return packageName;
|
||||
}
|
||||
|
||||
private void showHideConfirmationDialog() {
|
||||
String appName = getString(R.string.app_name);
|
||||
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
|
||||
builder.setTitle(R.string.panic_hide_warning_title);
|
||||
builder.setMessage(getString(R.string.panic_hide_warning_message, appName,
|
||||
HidingManager.getUnhidePin(getActivity()), getString(R.string.hiding_calculator)));
|
||||
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
// enable "exit" if "hiding" gets enabled
|
||||
prefExit.setChecked(true);
|
||||
// dismiss, but not cancel dialog
|
||||
dialogInterface.dismiss();
|
||||
}
|
||||
});
|
||||
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialogInterface, int i) {
|
||||
dialogInterface.cancel();
|
||||
}
|
||||
});
|
||||
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialogInterface) {
|
||||
prefHide.setChecked(false);
|
||||
prefResetRepos.setChecked(false);
|
||||
}
|
||||
});
|
||||
builder.setView(R.layout.dialog_app_hiding);
|
||||
builder.create().show();
|
||||
}
|
||||
|
||||
}
|
@ -1,174 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.ContentValues;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.util.Log;
|
||||
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.data.Apk;
|
||||
import org.fdroid.fdroid.data.DBHelper;
|
||||
import org.fdroid.fdroid.data.InstalledApp;
|
||||
import org.fdroid.fdroid.data.InstalledAppProvider;
|
||||
import org.fdroid.fdroid.data.Repo;
|
||||
import org.fdroid.fdroid.data.RepoProvider;
|
||||
import org.fdroid.fdroid.data.Schema;
|
||||
import org.fdroid.fdroid.installer.Installer;
|
||||
import org.fdroid.fdroid.installer.InstallerService;
|
||||
import org.fdroid.fdroid.installer.PrivilegedInstaller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
|
||||
import info.guardianproject.panic.Panic;
|
||||
import info.guardianproject.panic.PanicResponder;
|
||||
|
||||
/**
|
||||
* This {@link AppCompatActivity} is purely to run events in response to a panic trigger.
|
||||
* It needs to be an {@code AppCompatActivity} rather than a {@link android.app.Service}
|
||||
* so that it can fetch some of the required information about what sent the
|
||||
* {@link Intent}. This is therefore an {@code AppCompatActivity} without any UI, which
|
||||
* is a special case in Android. All the code must be in
|
||||
* {@link #onCreate(Bundle)} and {@link #finish()} must be called at the end of
|
||||
* that method.
|
||||
*
|
||||
* @see PanicResponder#receivedTriggerFromConnectedApp(AppCompatActivity)
|
||||
*/
|
||||
public class PanicResponderActivity extends AppCompatActivity {
|
||||
|
||||
private static final String TAG = PanicResponderActivity.class.getSimpleName();
|
||||
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
Intent intent = getIntent();
|
||||
if (!Panic.isTriggerIntent(intent)) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
// received intent from panic app
|
||||
Log.i(TAG, "Received Panic Trigger...");
|
||||
|
||||
final Preferences preferences = Preferences.get();
|
||||
|
||||
boolean receivedTriggerFromConnectedApp = PanicResponder.receivedTriggerFromConnectedApp(this);
|
||||
final boolean runningAppUninstalls = PrivilegedInstaller.isDefault(this);
|
||||
|
||||
ArrayList<String> wipeList = new ArrayList<>(preferences.getPanicWipeSet());
|
||||
preferences.setPanicWipeSet(Collections.<String>emptySet());
|
||||
preferences.setPanicTmpSelectedSet(Collections.<String>emptySet());
|
||||
|
||||
if (receivedTriggerFromConnectedApp && runningAppUninstalls && wipeList.size() > 0) {
|
||||
|
||||
// if this app (e.g. F-Droid) is to be deleted, do it last
|
||||
if (wipeList.contains(getPackageName())) {
|
||||
wipeList.remove(getPackageName());
|
||||
wipeList.add(getPackageName());
|
||||
}
|
||||
|
||||
final Context context = this;
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
|
||||
final String lastToUninstall = wipeList.get(wipeList.size() - 1);
|
||||
final BroadcastReceiver receiver = new BroadcastReceiver() {
|
||||
@Override
|
||||
public void onReceive(Context context, Intent intent) {
|
||||
switch ((intent.getAction())) {
|
||||
case Installer.ACTION_UNINSTALL_INTERRUPTED:
|
||||
case Installer.ACTION_UNINSTALL_COMPLETE:
|
||||
latch.countDown();
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
lbm.registerReceiver(receiver, Installer.getUninstallIntentFilter(lastToUninstall));
|
||||
|
||||
for (String packageName : wipeList) {
|
||||
InstalledApp installedApp = InstalledAppProvider.Helper.findByPackageName(context, packageName);
|
||||
InstallerService.uninstall(context, new Apk(installedApp));
|
||||
}
|
||||
|
||||
// wait for apps to uninstall before triggering final responses
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
latch.await(10, TimeUnit.MINUTES);
|
||||
} catch (InterruptedException e) {
|
||||
// ignored
|
||||
}
|
||||
lbm.unregisterReceiver(receiver);
|
||||
if (preferences.panicResetRepos()) {
|
||||
resetRepos(context);
|
||||
}
|
||||
if (preferences.panicHide()) {
|
||||
HidingManager.hide(context);
|
||||
}
|
||||
if (preferences.panicExit()) {
|
||||
exitAndClear();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
} else if (receivedTriggerFromConnectedApp) {
|
||||
if (preferences.panicResetRepos()) {
|
||||
resetRepos(this);
|
||||
}
|
||||
// Performing destructive panic response
|
||||
if (preferences.panicHide()) {
|
||||
Log.i(TAG, "Hiding app...");
|
||||
HidingManager.hide(this);
|
||||
}
|
||||
}
|
||||
|
||||
// exit and clear, if not deactivated
|
||||
if (!runningAppUninstalls && preferences.panicExit()) {
|
||||
exitAndClear();
|
||||
}
|
||||
finish();
|
||||
}
|
||||
|
||||
static void resetRepos(Context context) {
|
||||
HashSet<String> enabledAddresses = new HashSet<>();
|
||||
HashSet<String> disabledAddresses = new HashSet<>();
|
||||
String[] defaultReposItems = DBHelper.loadInitialRepos(context).toArray(new String[0]);
|
||||
for (int i = 1; i < defaultReposItems.length; i += DBHelper.REPO_XML_ITEM_COUNT) {
|
||||
if ("1".equals(defaultReposItems[i + 3])) {
|
||||
enabledAddresses.add(defaultReposItems[i]);
|
||||
} else {
|
||||
disabledAddresses.add(defaultReposItems[i]);
|
||||
}
|
||||
}
|
||||
|
||||
List<Repo> repos = RepoProvider.Helper.all(context);
|
||||
for (Repo repo : repos) {
|
||||
ContentValues values = new ContentValues(1);
|
||||
if (enabledAddresses.contains(repo.address)) {
|
||||
values.put(Schema.RepoTable.Cols.IN_USE, true);
|
||||
RepoProvider.Helper.update(context, repo, values);
|
||||
} else if (disabledAddresses.contains(repo.address)) {
|
||||
values.put(Schema.RepoTable.Cols.IN_USE, false);
|
||||
RepoProvider.Helper.update(context, repo, values);
|
||||
} else {
|
||||
RepoProvider.Helper.remove(context, repo.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void exitAndClear() {
|
||||
ExitActivity.exitAndRemoveFromRecentApps(this);
|
||||
if (Build.VERSION.SDK_INT >= 21) {
|
||||
finishAndRemoveTask();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.views.installed.InstalledAppListAdapter;
|
||||
import org.fdroid.fdroid.views.installed.InstalledAppListItemController;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class SelectInstalledAppListAdapter extends InstalledAppListAdapter {
|
||||
private final Set<String> selectedApps;
|
||||
|
||||
SelectInstalledAppListAdapter(AppCompatActivity activity) {
|
||||
super(activity);
|
||||
Preferences prefs = Preferences.get();
|
||||
selectedApps = prefs.getPanicWipeSet();
|
||||
prefs.setPanicTmpSelectedSet(selectedApps);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public InstalledAppListItemController onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
View view = activity.getLayoutInflater().inflate(R.layout.installed_app_list_item, parent, false);
|
||||
return new SelectInstalledAppListItemController(activity, view, selectedApps);
|
||||
}
|
||||
}
|
@ -1,39 +0,0 @@
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.view.View;
|
||||
|
||||
import org.fdroid.fdroid.AppUpdateStatusManager;
|
||||
import org.fdroid.fdroid.data.App;
|
||||
import org.fdroid.fdroid.views.apps.AppListItemState;
|
||||
import org.fdroid.fdroid.views.installed.InstalledAppListItemController;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
/**
|
||||
* Shows the currently installed apps as a selectable list.
|
||||
*/
|
||||
public class SelectInstalledAppListItemController extends InstalledAppListItemController {
|
||||
|
||||
private final Set<String> selectedApps;
|
||||
|
||||
public SelectInstalledAppListItemController(AppCompatActivity activity, View itemView, Set<String> selectedApps) {
|
||||
super(activity, itemView);
|
||||
this.selectedApps = selectedApps;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
protected AppListItemState getCurrentViewState(
|
||||
@NonNull App app, @Nullable AppUpdateStatusManager.AppUpdateStatus appStatus) {
|
||||
return new AppListItemState(app).setCheckBoxStatus(selectedApps.contains(app.packageName));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onActionButtonPressed(App app) {
|
||||
super.onActionButtonPressed(app);
|
||||
}
|
||||
}
|
@ -1,133 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com
|
||||
* Copyright (C) 2009 Roberto Jacinto, roberto.jacinto@caixamagica.pt
|
||||
*
|
||||
* 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, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
||||
*/
|
||||
|
||||
package org.fdroid.fdroid.panic;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.database.Cursor;
|
||||
import android.os.Bundle;
|
||||
import android.view.Menu;
|
||||
import android.view.MenuItem;
|
||||
import android.view.View;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.google.android.material.appbar.MaterialToolbar;
|
||||
|
||||
import org.fdroid.fdroid.FDroidApp;
|
||||
import org.fdroid.fdroid.Preferences;
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.data.InstalledAppProvider;
|
||||
import org.fdroid.fdroid.views.installed.InstalledAppListAdapter;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.loader.app.LoaderManager;
|
||||
import androidx.loader.content.CursorLoader;
|
||||
import androidx.loader.content.Loader;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
public class SelectInstalledAppsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
|
||||
|
||||
private InstalledAppListAdapter adapter;
|
||||
private RecyclerView appList;
|
||||
private TextView emptyState;
|
||||
private int checkId;
|
||||
|
||||
private Preferences prefs;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
FDroidApp fdroidApp = (FDroidApp) getApplication();
|
||||
fdroidApp.applyPureBlackBackgroundInDarkTheme(this);
|
||||
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
setContentView(R.layout.installed_apps_layout);
|
||||
|
||||
MaterialToolbar toolbar = findViewById(R.id.toolbar);
|
||||
toolbar.setTitle(getString(R.string.panic_add_apps_to_uninstall));
|
||||
setSupportActionBar(toolbar);
|
||||
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
|
||||
|
||||
adapter = new SelectInstalledAppListAdapter(this);
|
||||
|
||||
appList = findViewById(R.id.app_list);
|
||||
appList.setHasFixedSize(true);
|
||||
appList.setLayoutManager(new LinearLayoutManager(this));
|
||||
appList.setAdapter(adapter);
|
||||
|
||||
emptyState = findViewById(R.id.empty_state);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
|
||||
prefs = Preferences.get();
|
||||
|
||||
// Starts a new or restarts an existing Loader in this manager
|
||||
getSupportLoaderManager().restartLoader(0, null, this);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
|
||||
return new CursorLoader(this, InstalledAppProvider.getAllAppsUri(), null, null, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) {
|
||||
adapter.setApps(cursor);
|
||||
|
||||
if (adapter.getItemCount() == 0) {
|
||||
appList.setVisibility(View.GONE);
|
||||
emptyState.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
appList.setVisibility(View.VISIBLE);
|
||||
emptyState.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoaderReset(@NonNull Loader<Cursor> loader) {
|
||||
adapter.setApps(null);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean onCreateOptionsMenu(Menu menu) {
|
||||
MenuItem menuItem = menu.add(R.string.menu_select_for_wipe);
|
||||
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
|
||||
checkId = menuItem.getItemId();
|
||||
menuItem.setIcon(R.drawable.check);
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressLint("ApplySharedPref")
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
finish();
|
||||
if (item.getItemId() == checkId) {
|
||||
prefs.setPanicWipeSet(prefs.getPanicTmpSelectedSet());
|
||||
return true;
|
||||
}
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
@ -1,239 +0,0 @@
|
||||
package org.fdroid.fdroid.views.main;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.UriPermission;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.hardware.usb.UsbDevice;
|
||||
import android.hardware.usb.UsbManager;
|
||||
import android.net.Uri;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.os.storage.StorageManager;
|
||||
import android.os.storage.StorageVolume;
|
||||
import android.provider.DocumentsContract;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.view.View;
|
||||
import android.widget.Button;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.fdroid.fdroid.R;
|
||||
import org.fdroid.fdroid.Utils;
|
||||
import org.fdroid.fdroid.nearby.SDCardScannerService;
|
||||
import org.fdroid.fdroid.nearby.SwapService;
|
||||
import org.fdroid.fdroid.nearby.TreeUriScannerIntentService;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
|
||||
/**
|
||||
* A splash screen encouraging people to start the swap process. The swap
|
||||
* process is quite heavy duty in that it fires up Bluetooth and/or WiFi
|
||||
* in order to scan for peers. As such, it is quite convenient to have a
|
||||
* more lightweight view to show in the main navigation that doesn't
|
||||
* automatically start doing things when the user touches the navigation
|
||||
* menu in the bottom navigation.
|
||||
* <p>
|
||||
* Lots of pieces of the nearby/swap functionality require that the user grant
|
||||
* F-Droid permissions at runtime on {@code android-23} and higher. On devices
|
||||
* that have a removable SD Card that is currently mounted, this will request
|
||||
* permission to read it, so that F-Droid can look for repos on the SD Card.
|
||||
* <p>
|
||||
* Once {@link Manifest.permission#READ_EXTERNAL_STORAGE} or
|
||||
* {@link Manifest.permission#WRITE_EXTERNAL_STORAGE} is granted for F-Droid,
|
||||
* then it can read any file on an SD Card and no more prompts are needed. For
|
||||
* USB OTG drives, the only way to get read permissions is to prompt the user
|
||||
* via {@link Intent#ACTION_OPEN_DOCUMENT_TREE}.
|
||||
* <p>
|
||||
* For write permissions, {@code android-19} and {@code android-20} devices are
|
||||
* basically screwed here. {@link Intent#ACTION_OPEN_DOCUMENT_TREE} was added
|
||||
* in {@code android-21}, and there does not seem to be any other way to get
|
||||
* write access to the the removable storage.
|
||||
*
|
||||
* @see TreeUriScannerIntentService
|
||||
* @see org.fdroid.fdroid.nearby.SDCardScannerService
|
||||
* <p>
|
||||
* TODO use {@link StorageManager#registerStorageVolumeCallback(Executor, StorageManager.StorageVolumeCallback)}
|
||||
*/
|
||||
public class NearbyViewBinder {
|
||||
public static final String TAG = "NearbyViewBinder";
|
||||
|
||||
private static File externalStorage = null;
|
||||
private static View swapView;
|
||||
|
||||
NearbyViewBinder(final AppCompatActivity activity, FrameLayout parent) {
|
||||
swapView = activity.getLayoutInflater().inflate(R.layout.main_tab_swap, parent, true);
|
||||
|
||||
TextView subtext = swapView.findViewById(R.id.both_parties_need_fdroid_text);
|
||||
subtext.setText(activity.getString(R.string.nearby_splash__both_parties_need_fdroid,
|
||||
activity.getString(R.string.app_name)));
|
||||
|
||||
ImageView nearbySplash = swapView.findViewById(R.id.image);
|
||||
|
||||
Button startButton = swapView.findViewById(R.id.find_people_button);
|
||||
startButton.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
final String coarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
|
||||
if (Build.VERSION.SDK_INT >= 23
|
||||
&& PackageManager.PERMISSION_GRANTED
|
||||
!= ContextCompat.checkSelfPermission(activity, coarseLocation)) {
|
||||
ActivityCompat.requestPermissions(activity, new String[]{coarseLocation},
|
||||
MainActivity.REQUEST_LOCATION_PERMISSIONS);
|
||||
} else {
|
||||
ContextCompat.startForegroundService(activity, new Intent(activity, SwapService.class));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (Build.VERSION.SDK_INT >= 21) {
|
||||
File[] dirs = activity.getExternalFilesDirs("");
|
||||
if (dirs != null) {
|
||||
for (File dir : dirs) {
|
||||
if (dir != null && Environment.isExternalStorageRemovable(dir)) {
|
||||
String state = Environment.getExternalStorageState(dir);
|
||||
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
|
||||
|| Environment.MEDIA_MOUNTED.equals(state)) {
|
||||
// remove Android/data/org.fdroid.fdroid/files to get root
|
||||
externalStorage = dir.getParentFile().getParentFile().getParentFile().getParentFile();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (Environment.isExternalStorageRemovable() &&
|
||||
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)
|
||||
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
|
||||
Log.i(TAG, "<21 isExternalStorageRemovable MEDIA_MOUNTED");
|
||||
externalStorage = Environment.getExternalStorageDirectory();
|
||||
}
|
||||
|
||||
final String writeExternalStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE;
|
||||
|
||||
if (externalStorage != null
|
||||
|| PackageManager.PERMISSION_GRANTED
|
||||
!= ContextCompat.checkSelfPermission(activity, writeExternalStorage)) {
|
||||
nearbySplash.setVisibility(View.GONE);
|
||||
TextView readExternalStorageText = swapView.findViewById(R.id.read_external_storage_text);
|
||||
readExternalStorageText.setVisibility(View.VISIBLE);
|
||||
Button requestReadExternalStorage = swapView.findViewById(R.id.request_read_external_storage_button);
|
||||
requestReadExternalStorage.setVisibility(View.VISIBLE);
|
||||
requestReadExternalStorage.setOnClickListener(new View.OnClickListener() {
|
||||
@RequiresApi(api = 21)
|
||||
@Override
|
||||
public void onClick(View v) {
|
||||
if (Build.VERSION.SDK_INT >= 23
|
||||
&& (externalStorage == null || !externalStorage.canRead())
|
||||
&& PackageManager.PERMISSION_GRANTED
|
||||
!= ContextCompat.checkSelfPermission(activity, writeExternalStorage)) {
|
||||
ActivityCompat.requestPermissions(activity, new String[]{writeExternalStorage},
|
||||
MainActivity.REQUEST_STORAGE_PERMISSIONS);
|
||||
} else {
|
||||
Toast.makeText(activity,
|
||||
activity.getString(R.string.scan_removable_storage_toast, externalStorage),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
SDCardScannerService.scan(activity);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
updateUsbOtg(activity);
|
||||
}
|
||||
|
||||
public static void updateUsbOtg(final Context context) {
|
||||
if (Build.VERSION.SDK_INT < 24) {
|
||||
return;
|
||||
}
|
||||
if (swapView == null) {
|
||||
Utils.debugLog(TAG, "swapView == null");
|
||||
return;
|
||||
}
|
||||
TextView storageVolumeText = swapView.findViewById(R.id.storage_volume_text);
|
||||
Button requestStorageVolume = swapView.findViewById(R.id.request_storage_volume_button);
|
||||
storageVolumeText.setVisibility(View.GONE);
|
||||
requestStorageVolume.setVisibility(View.GONE);
|
||||
|
||||
final StorageManager storageManager = ContextCompat.getSystemService(context, StorageManager.class);
|
||||
for (final StorageVolume storageVolume : storageManager.getStorageVolumes()) {
|
||||
if (storageVolume.isRemovable() && !storageVolume.isPrimary()) {
|
||||
Log.i(TAG, "StorageVolume: " + storageVolume);
|
||||
Intent tmpIntent = null;
|
||||
if (Build.VERSION.SDK_INT < 29) {
|
||||
tmpIntent = storageVolume.createAccessIntent(null);
|
||||
} else {
|
||||
tmpIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
|
||||
tmpIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI,
|
||||
Uri.parse("content://"
|
||||
+ TreeUriScannerIntentService.EXTERNAL_STORAGE_PROVIDER_AUTHORITY
|
||||
+ "/tree/"
|
||||
+ storageVolume.getUuid()
|
||||
+ "%3A/document/"
|
||||
+ storageVolume.getUuid()
|
||||
+ "%3A"));
|
||||
}
|
||||
if (tmpIntent == null) {
|
||||
Utils.debugLog(TAG, "Got null Storage Volume access Intent");
|
||||
return;
|
||||
}
|
||||
final Intent intent = tmpIntent;
|
||||
|
||||
storageVolumeText.setVisibility(View.VISIBLE);
|
||||
|
||||
String text = storageVolume.getDescription(context);
|
||||
if (!TextUtils.isEmpty(text)) {
|
||||
requestStorageVolume.setText(text);
|
||||
UsbDevice usb = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
|
||||
if (usb != null) {
|
||||
text = String.format("%s (%s %s)", text, usb.getManufacturerName(), usb.getProductName());
|
||||
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
|
||||
}
|
||||
}
|
||||
|
||||
requestStorageVolume.setVisibility(View.VISIBLE);
|
||||
requestStorageVolume.setOnClickListener(new View.OnClickListener() {
|
||||
@Override
|
||||
@RequiresApi(api = 24)
|
||||
public void onClick(View v) {
|
||||
List<UriPermission> list = context.getContentResolver().getPersistedUriPermissions();
|
||||
if (list != null) for (UriPermission uriPermission : list) {
|
||||
Uri uri = uriPermission.getUri();
|
||||
if (uri.getPath().equals(String.format("/tree/%s:", storageVolume.getUuid()))) {
|
||||
intent.setData(uri);
|
||||
TreeUriScannerIntentService.onActivityResult(context, intent);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
AppCompatActivity activity = null;
|
||||
if (context instanceof AppCompatActivity) {
|
||||
activity = (AppCompatActivity) context;
|
||||
} else if (swapView != null && swapView.getContext() instanceof AppCompatActivity) {
|
||||
activity = (AppCompatActivity) swapView.getContext();
|
||||
}
|
||||
|
||||
if (activity != null) {
|
||||
activity.startActivityForResult(intent, MainActivity.REQUEST_STORAGE_ACCESS);
|
||||
} else {
|
||||
// scan in the background without requesting permissions
|
||||
Toast.makeText(context.getApplicationContext(),
|
||||
context.getString(R.string.scan_removable_storage_toast, externalStorage),
|
||||
Toast.LENGTH_SHORT).show();
|
||||
SDCardScannerService.scan(context);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Before Width: | Height: | Size: 213 B |
Before Width: | Height: | Size: 246 B |
Before Width: | Height: | Size: 8.9 KiB |
Before Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 94 B |
Before Width: | Height: | Size: 107 B |
Before Width: | Height: | Size: 1.6 KiB |
Before Width: | Height: | Size: 2.7 KiB |
Before Width: | Height: | Size: 112 B |
Before Width: | Height: | Size: 139 B |