Compare commits

..
Author SHA1 Message Date
Alex Knop a4a20c4b70 small fix
Signed-off-by: Alex Knop <[email protected]>
2025-08-22 13:56:21 -04:00
Alex Knop caa2dc310b Fix Method ignores exceptional return value
Signed-off-by: Alex Knop <[email protected]>
2025-08-22 13:46:14 -04:00
380 changed files with 5849 additions and 18862 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:noble@sha256:66460d557b25769b102175144d538d88219c077c678a49af4afca6fbfc1b5252
FROM ubuntu:noble@sha256:7c06e91f61fa88c08cc74f7e1b7c69ae24910d745357e0dfe1d2c0322aaf20f9
ARG DEBIAN_FRONTEND=noninteractive
ENV ANDROID_HOME=/usr/lib/android-sdk
-1
View File
@@ -27,7 +27,6 @@ concurrency:
jobs:
analysis:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Disabled on forks
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
with:
distribution: "temurin"
java-version: 17
- uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- uses: gradle/actions/wrapper-validation@017a9effdb900e5b5b2fddfb590a105619dca3c3 # v4.4.2
- name: Build ${{ matrix.flavor }}
run: |
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
+2 -2
View File
@@ -43,7 +43,7 @@ jobs:
with:
swap-size-gb: 10
- name: Initialize CodeQL
uses: github/codeql-action/init@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/init@3c3833e0f8c1c83d449a7478aa59c036a9165498 # v3.29.11
with:
languages: ${{ matrix.language }}
- name: Set up JDK 17
@@ -57,4 +57,4 @@ jobs:
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
./gradlew assembleDebug
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/analyze@3c3833e0f8c1c83d449a7478aa59c036a9165498 # v3.29.11
+10 -7
View File
@@ -45,11 +45,14 @@ jobs:
LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mkdir -p "$HOME/.gradle"
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" > "$HOME/.gradle/gradle.properties"
echo "org.gradle.caching=true; org.gradle.parallel=true; org.gradle.configureondemand=true; kapt.incremental.apt=true" >> "$HOME/.gradle/gradle.properties"
sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" "app/build.gradle"
sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" "app/build.gradle"
mkdir -p $HOME/.gradle
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" > $HOME/.gradle/gradle.properties
echo "org.gradle.caching=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.parallel=true" >> $HOME/.gradle/gradle.properties
echo "org.gradle.configureondemand=true" >> $HOME/.gradle/gradle.properties
echo "kapt.incremental.apt=true" >> $HOME/.gradle/gradle.properties
sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" app/build.gradle
sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" app/build.gradle
./gradlew assembleQaDebug
$(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign --ks-pass pass:"$KS_PASS" --key-pass pass:"$KEY_PASS" --ks-key-alias key0 --ks ".github/workflows/QA_keystore.jks" app/build/outputs/apk/qa/debug/*qa-debug*.apk
.github/workflows/uploadArtifact.sh "$LOG_USERNAME" "$LOG_PASSWORD" "${{github.event.number}}" "${{github.event.number}}" "$GITHUB_TOKEN"
$(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign --ks-pass pass:$KS_PASS --key-pass pass:$KEY_PASS --ks-key-alias key0 --ks .github/workflows/QA_keystore.jks app/build/outputs/apk/qa/debug/*qa-debug*.apk
.github/workflows/uploadArtifact.sh $LOG_USERNAME $LOG_PASSWORD ${{github.event.number}} ${{github.event.number}} $GITHUB_TOKEN
+1 -1
View File
@@ -24,4 +24,4 @@ jobs:
persist-credentials: false
- name: REUSE Compliance Check
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
uses: fsfe/reuse-action@bb774aa972c2a89ff34781233d275075cbddf542 # v5.0.0
+2 -2
View File
@@ -34,7 +34,7 @@ jobs:
persist-credentials: false
- name: "Run analysis"
uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2
with:
results_file: results.sarif
results_format: sarif
@@ -42,6 +42,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/upload-sarif@3c3833e0f8c1c83d449a7478aa59c036a9165498 # v3.29.11
with:
sarif_file: results.sarif
+3 -3
View File
@@ -28,14 +28,14 @@ jobs:
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
- name: Gradle cache
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}
- name: AVD cache
uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
id: avd-cache
with:
path: |
@@ -102,7 +102,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "${{ matrix.color }}-${{ matrix.scheme }}" "Screenshot" ${{github.event.number}}
- name: Archive Espresso results
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: ${{ always() }}
with:
name: Report-${{ matrix.color }}-${{ matrix.scheme }}
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
issues: write
pull-requests: write
steps:
- uses: actions/stale@5f858e3efba33a5ca4407a664cc011ad407f2008 # v10.1.0
- uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9.1.0
with:
days-before-stale: 28
days-before-close: 14
+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
if: ${{ always() }}
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
uses: gradle/actions/setup-gradle@017a9effdb900e5b5b2fddfb590a105619dca3c3 # v4.4.2
- name: Run unit tests with coverage
run: ./gradlew jacocoTestGplayDebugUnitTest
- name: Upload failing results
@@ -42,14 +42,14 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "test" "Unit" ${{github.event.number}}
- name: Upload coverage to codecov
uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
uses: codecov/codecov-action@fdcc8476540edceab3de004e990f80d881c6cc00 # v5.5.0
with:
token: ${{ secrets.CODECOV_TOKEN }}
flags: unit
fail_ci_if_error: true
- name: Upload jacoco artifacts
if: ${{ failure() }}
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: test-results
path: app/build/reports/tests/testGplayDebugUnitTest/
-92
View File
@@ -1,95 +1,3 @@
## 3.33.0 (September 10, 2025)
- Migrate to Glide 4
- Performance improvements
- Fix gallery image scaling
- Bugfixes
Minimum: NC 18 Server, Android 8.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/112
## 3.32.3 (August 21, 2025)
- Bugfixes
Minimum: NC 18 Server, Android 8.0 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/114
## 3.32.2 (July 18, 2025)
- Resolved image blurriness issue.
- Fixed crash occurring in the conflict resolution dialog.
- Addressed crash in the upload finish receiver event handler.
Minimum: NC 18 Server, Android 8.0 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/115
## 3.32.1 (July 14, 2025)
- Bug fixes.
Minimum: NC 18 Server, Android 8.0 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/113
## 3.32.0 (July 2, 2025)
- Minimum supported Android version is 8.0.
- Scrolling performance has been increased in the media tab.
- Multi-select feature added to the media tab.
- Custom share permissions have been added.
- Bug fixes.
Minimum: NC 18 Server, Android 8.0 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/107
## 3.31.4 (June 3, 2025)
- Add missing auto migration
Minimum: NC 18 Server, Android 7.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/110
## 3.31.3 (May 28, 2025)
- fix simple sign up
- bugfixes
- update translations
Minimum: NC 18 Server, Android 7.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/110
## 3.31.2 (May 20, 2025)
- bring back MANAGE_EXTERNAL_STORAGE permission
Minimum: NC 18 Server, Android 7.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/108
## 3.31.1 (April 3, 2025)
- Various bug fixes and performance enhancements
Minimum: NC 18 Server, Android 7.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/108
## 3.31.0 (February 25, 2025)
- New share layout
- Various bug fixes and performance enhancements
Minimum: NC 18 Server, Android 7.1 Nougat
For a full list, please see https://github.com/nextcloud/android/milestone/100
## 3.30.7 (January 6, 2025)
- Fix crash of auto upload settings
-3
View File
@@ -12,9 +12,6 @@ height="80">](https://play.google.com/store/apps/details?id=com.nextcloud.client
[<img src="https://f-droid.org/badge/get-it-on.png"
alt="Get it on F-Droid"
height="80">](https://f-droid.org/packages/com.nextcloud.client/)
[<img src="https://github.com/user-attachments/assets/713d71c5-3dec-4ec4-a3f2-8d28d025a9c6"
alt="Get it with Obtainium"
height="80">](https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22com.nextcloud.client%22%2C%22url%22%3A%22https%3A%2F%2Fgithub.com%2Fnextcloud%2Fandroid%22%2C%22author%22%3A%22nextcloud%22%2C%22name%22%3A%22Nextcloud%22%2C%22preferredApkIndex%22%3A0%2C%22additionalSettings%22%3A%22%7B%5C%22includePrereleases%5C%22%3Afalse%2C%5C%22fallbackToOlderReleases%5C%22%3Atrue%2C%5C%22filterReleaseTitlesByRegEx%5C%22%3A%5C%22%5C%22%2C%5C%22filterReleaseNotesByRegEx%5C%22%3A%5C%22%5C%22%2C%5C%22verifyLatestTag%5C%22%3Afalse%2C%5C%22sortMethodChoice%5C%22%3A%5C%22date%5C%22%2C%5C%22useLatestAssetDateAsReleaseDate%5C%22%3Afalse%2C%5C%22releaseTitleAsVersion%5C%22%3Afalse%2C%5C%22trackOnly%5C%22%3Afalse%2C%5C%22versionExtractionRegEx%5C%22%3A%5C%22%5C%22%2C%5C%22matchGroupToUse%5C%22%3A%5C%22%5C%22%2C%5C%22versionDetection%5C%22%3Atrue%2C%5C%22releaseDateAsVersion%5C%22%3Afalse%2C%5C%22useVersionCodeAsOSVersion%5C%22%3Afalse%2C%5C%22apkFilterRegEx%5C%22%3A%5C%22%5Enextcloud.*%5C%22%2C%5C%22invertAPKFilter%5C%22%3Afalse%2C%5C%22autoApkFilterByArch%5C%22%3Atrue%2C%5C%22appName%5C%22%3A%5C%22%5C%22%2C%5C%22appAuthor%5C%22%3A%5C%22%5C%22%2C%5C%22shizukuPretendToBeGooglePlay%5C%22%3Afalse%2C%5C%22allowInsecure%5C%22%3Afalse%2C%5C%22exemptFromBackgroundUpdates%5C%22%3Afalse%2C%5C%22skipUpdateNotifications%5C%22%3Afalse%2C%5C%22about%5C%22%3A%5C%22Nextcloud%20ist%20eine%20Cloudanwendung%2C%20die%20selbst%20gehostet%20werden%20kann.%5C%22%2C%5C%22refreshBeforeDownload%5C%22%3Atrue%7D%22%2C%22overrideSource%22%3Anull%7D)
Signing certificate fingerprint to [verify](https://developer.android.com/studio/command-line/apksigner#usage-verify) the APK:
- APK with "gplay" name, found [here](https://github.com/nextcloud/android/releases) or distributed via Google Play Store
-120
View File
@@ -1,120 +0,0 @@
<!--
~ SPDX-FileCopyrightText: 2025 Saeed <[email protected]>
~ SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
-->
# تطبيق [Nextcloud](https://nextcloud.com)لأجهزة أندرويد 📱
[![حالة REUSE](https://api.reuse.software/badge/github.com/nextcloud/android)](https://api.reuse.software/info/github.com/nextcloud/android)
[![حالة البناء](https://drone.nextcloud.com/api/badges/nextcloud/android/status.svg)](https://drone.nextcloud.com/nextcloud/android)
[![تقييم Codacy](https://app.codacy.com/project/badge/Grade/fb4cf26336774ee3a5c9adfe829c41aa)](https://app.codacy.com/gh/nextcloud/android/dashboard)
[![الإصدارات](https://img.shields.io/github/release/nextcloud/android.svg)](https://github.com/nextcloud/android/releases/latest)
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png" alt="تحميل من Google Play" height="80">](https://play.google.com/store/apps/details?id=com.nextcloud.client)
[<img src="https://f-droid.org/badge/get-it-on.png" alt="احصل عليه من F-Droid" height="80">](https://f-droid.org/packages/com.nextcloud.client/)
## التحقق من توقيع التطبيق 🔐
للتأكد من صحة ملف APK:
- ملف APK باسم "gplay" متوفر [هنا](https://github.com/nextcloud/android/releases) أو عبر متجر Google Play
- ملف APK باسم "nextcloud" متوفر [هنا](https://github.com/nextcloud/android/releases)
- غير مناسب لتحميلات F-Droid، لأن F-Droid يقوم بتوقيعه بنفسه
```plaintext
SHA-256: fb009522f65e25802261b67b10a45fd70e610031976f40b28a649e152ded0373
SHA-1: 74aa1702e714941be481e1f7ce4a8f779c19dcea
```
**تطبيق Nextcloud لأندرويد يتيح لك إدارة بياناتك بسهولة على خادم Nextcloud الخاص بك.**
## الحصول على الدعم 🆘
إذا واجهت مشكلة أو لديك سؤال، يمكنك زيارة [منتدى الدعم](https://help.nextcloud.com/c/clients/android).
إذا اكتشفت خطأ أو لديك اقتراح لتحسين التطبيق، يمكنك [فتح قضية جديدة على GitHub](https://github.com/nextcloud/android/issues).
إذا لم تكن متأكدًا ما إذا كانت المشكلة ناتجة عن التطبيق أو الإعدادات أو الخادم، فابدأ بالسؤال في المنتدى، ثم عد إلى GitHub إذا لزم الأمر.
> ملاحظة: هذا المستودع خاص بتطبيق أندرويد فقط. إذا كانت المشكلة في الخادم، يرجى التواصل مع [فريق خادم Nextcloud](https://github.com/nextcloud/server).
## كيف تساهم في المشروع 🚀
هناك العديد من الطرق للمساهمة، سواء كنت مبرمجًا أو لا:
- مساعدة المستخدمين في المنتدى: https://help.nextcloud.com
- ترجمة التطبيق عبر [Transifex](https://app.transifex.com/nextcloud/nextcloud/android/)
- الإبلاغ عن المشاكل أو تقديم اقتراحات عبر [GitHub Issues](https://github.com/nextcloud/android/issues/new/choose)
- تنفيذ إصلاحات أو تحسينات عبر Pull Requests
- مراجعة [طلبات الدمج](https://github.com/nextcloud/android/pulls)
- اختبار النسخ التجريبية أو اليومية أو المرشحة للإصدار
- تحسين [التوثيق](https://github.com/nextcloud/documentation/)
- اختبار الميزات الأساسية في آخر إصدار مستقر
- تعلم كيفية جمع سجلات الأخطاء (logcat) لتقديم تقارير دقيقة
## إرشادات المساهمة والترخيص 📜
- الترخيص: [GPLv2](https://github.com/nextcloud/android/blob/master/LICENSE.txt)
- جميع المساهمات بعد 16 يونيو 2016 تعتبر مرخصة تحت AGPLv3 أو أي إصدار لاحق
- لا حاجة لتوقيع اتفاقية مساهم (CLA)
- يُفضل إضافة السطر التالي في رأس الملف عند إجراء تغييرات كبيرة:
```plaintext
SPDX-FileCopyrightText: <السنة> <اسمك> <بريدك الإلكتروني>
```
يرجى قراءة [مدونة السلوك](https://nextcloud.com/community/code-of-conduct/) لضمان بيئة تعاون إيجابية.
راجع أيضًا [إرشادات المساهمة](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md).
## ابدأ بالمساهمة 🔧
- اقرأ [SETUP.md](https://github.com/nextcloud/android/blob/master/SETUP.md) و[CONTRIBUTING.md](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md)
- قم بعمل fork للمستودع وابدأ بإرسال Pull Requests إلى فرع master
- يمكنك البدء بمراجعة [طلبات الدمج](https://github.com/nextcloud/android/pulls) أو العمل على [القضايا المبتدئة](https://github.com/nextcloud/android/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
## جمع سجلات الأخطاء (logcat) 🔍
### على لينكس:
- فعّل USB-Debugging على هاتفك
- افتح الطرفية وأدخل:
```bash
adb logcat --pid=$(adb shell pidof -s 'com.nextcloud.client') > logcatOutput.txt
```
> تأكد من تثبيت [adb](https://developer.android.com/studio/releases/platform-tools.html)
### على ويندوز:
- حمّل [Minimal ADB and Fastboot](https://forum.xda-developers.com/t/tool-minimal-adb-and-fastboot-2-9-18.2317790/#post-42407269)
- فعّل USB-Debugging
- افتح البرنامج وأدخل:
```bash
adb shell pidof -s 'com.nextcloud.client'
```
- استخدم الناتج كـ `<processID>` في الأمر التالي:
```bash
adb logcat --pid=<processID> > "%USERPROFILE%\Downloads\logcatOutput.txt"
```
### على الجهاز (مع صلاحيات root):
```bash
su
logcat -d --pid $(pidof -s com.nextcloud.client) -f /sdcard/logcatOutput.txt
```
أو استخدم تطبيقات مثل [CatLog](https://play.google.com/store/apps/details?id=com.nolanlawson.logcat) أو [aLogcat](https://play.google.com/store/apps/details?id=org.jtb.alogcat)
## النسخة التطويرية 🛠️
- [تحميل مباشر للـ APK](https://download.nextcloud.com/android/dev/latest.apk)
- [F-Droid النسخة التجريبية](https://f-droid.org/en/packages/com.nextcloud.android.beta/)
## المشاكل المعروفة والأسئلة الشائعة
### الإشعارات الفورية لا تعمل في نسخ F-Droid
بسبب اعتمادها على خدمات Google Play، لا تعمل الإشعارات الفورية في نسخ F-Droid حاليًا.
+104 -161
View File
@@ -19,8 +19,8 @@ buildscript {
classpath libs.spotbugs.gradle.plugin
classpath libs.kotlin.gradle.plugin
classpath libs.detekt.gradle.plugin
classpath libs.commons.httpclient.commons.httpclient // remove after entire switch to lib v2
classpath libs.shot
classpath "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
classpath "com.karumi:shot:6.1.0"
classpath "org.jacoco:org.jacoco.core:$jacoco_version"
classpath "org.jacoco:org.jacoco.report:$jacoco_version"
classpath "org.jacoco:org.jacoco.agent:$jacoco_version"
@@ -32,7 +32,6 @@ plugins {
alias(libs.plugins.spotless)
alias(libs.plugins.kapt)
alias(libs.plugins.ksp) apply false
alias(libs.plugins.kotlin.serialization)
}
apply plugin: "com.android.application"
@@ -68,16 +67,12 @@ configurations.configureEach {
useVersion(checkerVersion)
because("https://github.com/google/ExoPlayer/issues/10007")
}
if (requested.group == "commons-logging" && requested.name == "commons-logging") {
useTarget("org.slf4j:jcl-over-slf4j:1.7.36")
}
}
}
// semantic versioning for version code
def versionMajor = 3
def versionMinor = 35
def versionMinor = 33
def versionPatch = 0
def versionBuild = 0 // 0-50=Alpha / 51-98=RC / 90-99=stable
@@ -115,9 +110,9 @@ android {
defaultConfig {
applicationId = "com.nextcloud.client"
minSdk = 27
targetSdk = 36
compileSdk = 36
minSdk = 26
targetSdk = 35
compileSdk = 35
buildConfigField "boolean", "CI", ciBuild.toString()
buildConfigField "boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString()
@@ -284,226 +279,174 @@ android {
}
dependencies {
// region Nextcloud library
implementation("com.github.nextcloud:android-library:$androidLibraryVersion") {
exclude group: "org.ogce", module: "xpp3" // unused in Android and brings wrong Junit version
}
// endregion
// region Splash Screen
// splash screen dependency ref: https://developer.android.com/develop/ui/views/launch/splash-screen/migrate
implementation libs.splashscreen
// endregion
// region Jetpack Compose
// Jetpack Compose
implementation(platform(libs.compose.bom))
implementation(libs.material.icons.core)
implementation(libs.compose.ui)
implementation(libs.compose.ui.graphics)
implementation(libs.compose.material3)
debugImplementation(libs.compose.ui.tooling)
implementation(libs.compose.ui.tooling.preview)
// endregion
// region Media3
// Media3
implementation libs.media3.ui
implementation libs.media3.session
implementation libs.media3.exoplayer
implementation libs.media3.datasource
// endregion
// region Room
// Room
implementation libs.room.runtime
ksp "androidx.room:room-compiler:$roomVersion"
androidTestImplementation libs.room.testing
// endregion
// region Espresso
// Espresso
androidTestImplementation libs.espresso.core
androidTestImplementation libs.espresso.contrib
androidTestImplementation libs.espresso.web
androidTestImplementation libs.espresso.accessibility
androidTestImplementation libs.espresso.intents
androidTestImplementation libs.espresso.idling.resource
// endregion
// region Glide
// Glide
implementation libs.glide
ksp libs.ksp
// endregion
// region UI
implementation libs.appcompat
implementation libs.webkit
implementation libs.cardview
implementation libs.exifinterface
implementation libs.fragment.ktx
// endregion
compileOnly "org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2"
// remove after entire switch to lib v2
implementation "commons-httpclient:commons-httpclient:3.1@jar" // remove after entire switch to lib v2
implementation "org.apache.jackrabbit:jackrabbit-webdav:2.13.5" // remove after entire switch to lib v2
implementation "androidx.constraintlayout:constraintlayout:2.2.1"
implementation "androidx.legacy:legacy-support-v4:1.0.0"
implementation "com.google.android.material:material:1.12.0"
implementation "com.jakewharton:disklrucache:2.0.2"
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation "androidx.webkit:webkit:1.14.0"
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.exifinterface:exifinterface:1.4.1"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.2"
implementation "androidx.lifecycle:lifecycle-service:2.9.2"
implementation "androidx.work:work-runtime:$workRuntime"
implementation "androidx.work:work-runtime-ktx:$workRuntime"
implementation "androidx.fragment:fragment-ktx:1.8.9"
implementation "com.github.albfernandez:juniversalchardet:2.5.0" // need this version for Android <7
compileOnly "com.google.code.findbugs:annotations:3.0.1u2"
implementation "commons-io:commons-io:2.20.0"
implementation "org.greenrobot:eventbus:3.3.1"
implementation "com.googlecode.ez-vcard:ez-vcard:0.12.1"
implementation "org.lukhnos:nnio:0.3.1"
implementation "org.bouncycastle:bcpkix-jdk18on:1.81"
implementation "com.google.code.gson:gson:2.13.1"
implementation "com.github.nextcloud-deps:sectioned-recyclerview:0.6.1"
implementation "com.github.Baseflow:PhotoView:2.3.0"
implementation "pl.droidsonroids.gif:android-gif-drawable:1.2.29"
implementation "com.github.nextcloud-deps:qrcodescanner:0.1.2.4" // "com.github.blikoon:QRCodeScanner:0.1.2"
implementation "com.google.android.flexbox:flexbox:3.0.0"
// region Worker
implementation libs.work.runtime
implementation libs.work.runtime.ktx
// endregion
implementation "com.caverock:androidsvg:1.4"
implementation "androidx.annotation:annotation:1.9.1"
implementation "com.vanniktech:emoji-google:0.21.0"
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.9.2")
// region Lifecycle
implementation libs.lifecycle.viewmodel.ktx
implementation libs.lifecycle.service
implementation(libs.lifecycle.runtime.ktx)
// endregion
// region JUnit
androidTestImplementation libs.junit
androidTestImplementation libs.rules
androidTestImplementation libs.runner
androidTestUtil libs.orchestrator
androidTestImplementation libs.core.ktx
androidTestImplementation libs.core.testing
// endregion
// region other libraries
compileOnly libs.org.jbundle.util.osgi.wrapped.org.apache.http.client
implementation libs.commons.httpclient.commons.httpclient // remove after entire switch to lib v2
implementation libs.jackrabbit.webdav // remove after entire switch to lib v2
implementation libs.constraintlayout
implementation libs.legacy.support.v4
implementation libs.material
implementation libs.disklrucache
implementation libs.juniversalchardet // need this version for Android <7
compileOnly libs.annotations
implementation libs.commons.io
implementation libs.eventbus
implementation libs.ez.vcard
implementation libs.nnio
implementation libs.bcpkix.jdk18on
implementation libs.gson
implementation libs.sectioned.recyclerview
implementation libs.photoview
implementation libs.android.gif.drawable
implementation libs.qrcodescanner // "com.github.blikoon:QRCodeScanner:0.1.2"
implementation libs.flexbox
implementation libs.androidsvg
implementation libs.annotation
implementation libs.emoji.google
// endregion
// region AppScan, document scanner not available on FDroid (generic) due to OpenCV binaries
// document scanner not available on FDroid (generic) due to OpenCV binaries
gplayImplementation project(":appscan")
huaweiImplementation project(":appscan")
qaImplementation project(":appscan")
// endregion
// region SpotBugs
spotbugsPlugins libs.findsecbugs.plugin
spotbugsPlugins libs.fb.contrib
// endregion
spotbugsPlugins "com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0"
spotbugsPlugins "com.mebigfatguy.fb-contrib:fb-contrib:7.6.12"
// region Dagger
implementation libs.dagger
implementation libs.dagger.android
implementation libs.dagger.android.support
implementation "com.google.dagger:dagger:$daggerVersion"
implementation "com.google.dagger:dagger-android:$daggerVersion"
implementation "com.google.dagger:dagger-android-support:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
kapt "com.google.dagger:dagger-android-processor:$daggerVersion"
// endregion
// region Crypto
implementation libs.conscrypt.android
// endregion
implementation "org.conscrypt:conscrypt-android:2.5.3"
// region Library
implementation libs.library
// endregion
implementation "me.zhanghai.android.fastscroll:library:1.3.0"
// region Shimmer
implementation libs.loaderviewlibrary
// endregion
// Shimmer animation
implementation "io.github.elye:loaderviewlibrary:3.0.0"
// region Markdown rendering
implementation libs.core
implementation libs.ext.strikethrough
implementation libs.ext.tables
implementation libs.ext.tasklist
implementation libs.html
implementation libs.syntax.highlight
implementation libs.prism4j
// dependencies for markdown rendering
implementation "io.noties.markwon:core:$markwonVersion"
implementation "io.noties.markwon:ext-strikethrough:$markwonVersion"
implementation "io.noties.markwon:ext-tables:$markwonVersion"
implementation "io.noties.markwon:ext-tasklist:$markwonVersion"
implementation "io.noties.markwon:html:$markwonVersion"
implementation "io.noties.markwon:syntax-highlight:$markwonVersion"
implementation "io.noties:prism4j:$prismVersion"
kapt "io.noties:prism4j-bundler:$prismVersion"
// endregion
// region Image cropping / rotation
implementation libs.android.image.cropper
// endregion
// dependencies for image cropping and rotation
implementation "com.vanniktech:android-image-cropper:4.6.0"
// region Maps
implementation libs.osmdroid.android
// endregion
implementation "org.osmdroid:osmdroid-android:6.1.20"
// region iCal4j
implementation(libs.ical4j) {
implementation("org.mnode.ical4j:ical4j:3.2.19") {
["org.apache.commons", "commons-logging"].each {
exclude group: "$it"
}
}
// endregion
// region LeakCanary
if (perfAnalysis) {
debugImplementation "com.squareup.leakcanary:leakcanary-android:2.14"
}
// endregion
// region Local Unit Test
testImplementation libs.junit.junit
testImplementation libs.mockito.core
testImplementation libs.test.core
testImplementation libs.json
testImplementation libs.mockito.kotlin
testImplementation libs.core.testing
// dependencies for local unit tests
testImplementation "junit:junit:4.13.2"
testImplementation "org.mockito:mockito-core:$mockitoVersion"
testImplementation "androidx.test:core:$androidxTestVersion"
testImplementation "org.json:json:20250517"
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
testImplementation "androidx.arch.core:core-testing:2.2.0"
testImplementation "io.mockk:mockk:$mockkVersion"
testImplementation libs.mockk.android
// endregion
testImplementation "io.mockk:mockk-android:$mockkVersion"
// region Mocking support
androidTestImplementation libs.dexopener // required to allow mocking on API 27 and older
androidTestImplementation libs.mockito.kotlin
androidTestImplementation libs.mockito.core
androidTestImplementation(libs.mockito.android)
androidTestImplementation libs.mockk.android
androidTestImplementation libs.screenshot.core
// endregion
// dependencies for instrumented tests
// JUnit4 Rules
androidTestImplementation "androidx.test.ext:junit:1.3.0"
androidTestImplementation "androidx.test:rules:$androidxTestVersion"
// Android JUnit Runner
androidTestImplementation "androidx.test:runner:1.7.0"
androidTestUtil "androidx.test:orchestrator:1.6.1"
androidTestImplementation "androidx.test:core-ktx:$androidxTestVersion"
// Mocking support
androidTestImplementation "com.github.tmurakami:dexopener:2.0.5" // required to allow mocking on API 27 and older
androidTestImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
androidTestImplementation "org.mockito:mockito-core:$mockitoVersion"
androidTestImplementation("org.mockito:mockito-android:$mockitoVersion")
androidTestImplementation "io.mockk:mockk-android:$mockkVersion"
androidTestImplementation "androidx.arch.core:core-testing:2.2.0"
androidTestImplementation "com.facebook.testing.screenshot:core:0.15.0"
// region UIAutomator
// UIAutomator - for cross-app UI tests, and to grant screen is turned on in Espresso tests
// androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
// fix conflict in dependencies; see http://g.co/androidstudio/app-test-app-conflict for details
// androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
androidTestImplementation libs.screengrab
// endregion
//androidTestImplementation "com.android.support:support-annotations:${supportLibraryVersion}"
androidTestImplementation "tools.fastlane:screengrab:2.1.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
// region Kotlin
implementation libs.kotlin.stdlib
// endregion
implementation "com.github.stateless4j:stateless4j:2.6.0"
// region Stateless
implementation libs.stateless4j
// endregion
// upon each update first test: new registration, receive push
gplayImplementation "com.google.firebase:firebase-messaging:25.0.0"
gplayImplementation "com.google.android.gms:play-services-base:18.7.2"
gplayImplementation "com.google.android.play:review-ktx:2.0.2"
// region Google Play dependencies, upon each update first test: new registration, receive push
gplayImplementation libs.firebase.messaging
gplayImplementation libs.play.services.base
gplayImplementation libs.review.ktx
// endregion
implementation "com.github.nextcloud.android-common:ui:$androidCommonLibraryVersion"
// region UI
implementation libs.ui
// endregion
// region Image loading
implementation libs.coil
// endregion
// kotlinx.serialization
implementation(libs.kotlinx.serialization.json)
implementation "io.coil-kt:coil:2.7.0"
}
configurations.configureEach {
resolutionStrategy {
force "org.objenesis:objenesis:3.4"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -24,7 +24,6 @@ import com.owncloud.android.AbstractIT
import com.owncloud.android.R
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.ui.fragment.EmptyListState
import com.owncloud.android.utils.EspressoIdlingResource
import com.owncloud.android.utils.ScreenshotTest
import org.junit.After
@@ -69,7 +68,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
listOfFilesFragment?.let {
it.setFabEnabled(false)
resetScrolling(true)
it.setEmptyListMessage(EmptyListState.LOADING)
it.setEmptyListLoadingMessage()
it.isLoading = false
}
}
@@ -99,7 +98,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
val fragment = sut.listOfFilesFragment
Assert.assertNotNull(fragment)
fragment!!.setFabEnabled(false)
fragment.setEmptyListMessage(EmptyListState.LOADING)
fragment.setEmptyListLoadingMessage()
fragment.isLoading = false
EspressoIdlingResource.decrement()
@@ -114,7 +113,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
EspressoIdlingResource.increment()
fragment.setFabEnabled(false)
fragment.setEmptyListMessage(EmptyListState.LOADING)
fragment.setEmptyListLoadingMessage()
fragment.isLoading = false
EspressoIdlingResource.decrement()
@@ -147,7 +146,7 @@ class FileDisplayActivityScreenshotIT : AbstractIT() {
listOfFilesFragment?.let {
it.setFabEnabled(false)
it.setEmptyListMessage(EmptyListState.LOADING)
it.setEmptyListLoadingMessage()
it.isLoading = false
}
}
@@ -119,8 +119,7 @@ class SyncedFoldersActivityIT : AbstractIT() {
onIdleSync {
EspressoIdlingResource.increment()
val dialog = sut.buildPowerCheckDialog()
sut.showPowerCheckDialog()
dialog.show()
EspressoIdlingResource.decrement()
val screenShotName = createName(testClassName + "_" + "showPowerCheckDialog", "")
@@ -12,7 +12,7 @@ import android.net.Uri
import android.os.Parcel
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.lib.common.OwnCloudBasicCredentials
import com.owncloud.android.lib.resources.status.NextcloudVersion
import com.owncloud.android.lib.resources.status.OwnCloudVersion
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotSame
@@ -31,7 +31,7 @@ class RegisteredUserTest {
val ownCloudAccount = OwnCloudAccount(uri, credentials)
val server = Server(
uri = URI(uri.toString()),
version = NextcloudVersion.nextcloud_31
version = OwnCloudVersion.nextcloud_18
)
return RegisteredUser(
account = account,
@@ -107,7 +107,7 @@ class DeepLinkHandlerTest {
fun createMockUser(serverBaseUrl: String): User {
val user = mock<User>()
val uri = URI.create(serverBaseUrl)
val server = Server(uri = uri, version = OwnCloudVersion.nextcloud_20)
val server = Server(uri = uri, version = OwnCloudVersion.nextcloud_19)
whenever(user.server).thenReturn(server)
return user
}
@@ -1,90 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.extensions
import android.graphics.Bitmap
import android.graphics.Color
import androidx.exifinterface.media.ExifInterface
import com.nextcloud.utils.rotateBitmapViaExif
import junit.framework.TestCase.assertEquals
import org.junit.Test
class BitmapRotationTests {
private fun createTestBitmap(): Bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888).apply {
setPixel(0, 0, Color.RED)
setPixel(1, 0, Color.GREEN)
setPixel(0, 1, Color.BLUE)
setPixel(1, 1, Color.YELLOW)
}
@Test
fun testRotateBitmapViaExifWhenGivenNullBitmapShouldReturnNull() {
val rotated = null.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_90)
assertEquals(null, rotated)
}
@Test
fun testRotateBitmapViaExifWhenGivenNormalOrientationShouldReturnSameBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_NORMAL)
assertEquals(bmp, rotated)
}
@Test
fun testRotateBitmapViaExifWhenGivenRotate90ShouldReturnRotatedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_90)!!
assertEquals(bmp.width, rotated.height)
assertEquals(bmp.height, rotated.width)
assertEquals(Color.BLUE, rotated.getPixel(0, 0))
assertEquals(Color.RED, rotated.getPixel(1, 0))
assertEquals(Color.YELLOW, rotated.getPixel(0, 1))
assertEquals(Color.GREEN, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenRotate180ShouldReturnRotatedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_180)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.YELLOW, rotated.getPixel(0, 0))
assertEquals(Color.BLUE, rotated.getPixel(1, 0))
assertEquals(Color.GREEN, rotated.getPixel(0, 1))
assertEquals(Color.RED, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenFlipHorizontalShouldReturnFlippedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_FLIP_HORIZONTAL)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.GREEN, rotated.getPixel(0, 0))
assertEquals(Color.RED, rotated.getPixel(1, 0))
assertEquals(Color.YELLOW, rotated.getPixel(0, 1))
assertEquals(Color.BLUE, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenFlipVerticalShouldReturnFlippedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_FLIP_VERTICAL)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.BLUE, rotated.getPixel(0, 0))
assertEquals(Color.YELLOW, rotated.getPixel(1, 0))
assertEquals(Color.RED, rotated.getPixel(0, 1))
assertEquals(Color.GREEN, rotated.getPixel(1, 1))
}
}
@@ -1,78 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.extensions
import android.graphics.Bitmap
import android.graphics.Color
import androidx.exifinterface.media.ExifInterface
import com.nextcloud.utils.extensions.getExifOrientation
import junit.framework.TestCase.assertEquals
import org.junit.After
import org.junit.Test
import java.io.File
class GetExifOrientationTests {
private val tempFiles = mutableListOf<File>()
@Suppress("MagicNumber")
private fun createTempImageFile(): File {
val file = File.createTempFile("test_image", ".jpg")
tempFiles.add(file)
val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888).apply {
setPixel(0, 0, Color.RED)
setPixel(1, 0, Color.GREEN)
setPixel(0, 1, Color.BLUE)
setPixel(1, 1, Color.YELLOW)
}
file.outputStream().use { out ->
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out)
}
return file
}
@After
fun cleanup() {
tempFiles.forEach { it.delete() }
}
@Test
fun testGetExifOrientationWhenExifIsRotate90ShouldReturnRotate90() {
val file = createTempImageFile()
val exif = ExifInterface(file.absolutePath)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_90.toString())
exif.saveAttributes()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_ROTATE_90, orientation)
}
@Test
fun testGetExifOrientationWhenExifIsRotate180ShouldReturnRotate180() {
val file = createTempImageFile()
val exif = ExifInterface(file.absolutePath)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_180.toString())
exif.saveAttributes()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_ROTATE_180, orientation)
}
@Test
fun testGetExifOrientationWhenExifIsUndefinedShouldReturnUndefined() {
val file = createTempImageFile()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_UNDEFINED, orientation)
}
}
@@ -1,176 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.extensions
import com.nextcloud.utils.extensions.isNotBlankAndEquals
import junit.framework.TestCase.assertFalse
import junit.framework.TestCase.assertTrue
import org.junit.Test
@Suppress("TooManyFunctions")
class StringExtensionTests {
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreNull() {
val str1: String? = null
val str2: String? = null
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenFirstStringIsNull() {
val str1: String? = null
val str2 = "hello"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenSecondStringIsNull() {
val str1 = "hello"
val str2: String? = null
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreEmpty() {
val str1 = ""
val str2 = ""
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenFirstStringIsEmpty() {
val str1 = ""
val str2 = "hello"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenSecondStringIsEmpty() {
val str1 = "hello"
val str2 = ""
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreWhitespaceOnly() {
val str1 = " "
val str2 = " \t "
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenFirstStringIsWhitespaceOnly() {
val str1 = " "
val str2 = "hello"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenSecondStringIsWhitespaceOnly() {
val str1 = "hello"
val str2 = " "
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenStringsAreDifferentButBothValid() {
val str1 = "hello"
val str2 = "world"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenStringsHaveDifferentCase() {
val str1 = "Hello"
val str2 = "hello"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenMixedCaseStrings() {
val str1 = "HeLLo WoRLd"
val str2 = "hello world"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenUppercaseStrings() {
val str1 = "HELLO"
val str2 = "hello"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreIdenticalAndValid() {
val str1 = "hello"
val str2 = "hello"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreIdenticalWithSpaces() {
val str1 = "hello world"
val str2 = "hello world"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreIdenticalSingleCharacter() {
val str1 = "a"
val str2 = "A"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothStringsAreIdenticalWithSpecialCharacters() {
val str1 = "hello@world!123"
val str2 = "HELLO@WORLD!123"
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenOneHasLeadingWhitespaceAndOtherDoesNot() {
val str1 = " hello"
val str2 = "HELLO"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenOneHasTrailingWhitespaceAndOtherDoesNot() {
val str1 = "hello"
val str2 = "HELLO "
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenBothHaveIdenticalWhitespacePaddingDifferentCase() {
val str1 = " hello "
val str2 = " HELLO "
assertTrue(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenMixedWhitespaceCharacters() {
val str1 = "\t"
val str2 = "\n"
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenOneIsNullAndOtherIsEmpty() {
val str1: String? = null
val str2 = ""
assertFalse(str1.isNotBlankAndEquals(str2))
}
@Test
fun testIsNotBlankAndEqualsWhenGivenOneIsNullAndOtherIsWhitespace() {
val str1: String? = null
val str2 = " "
assertFalse(str1.isNotBlankAndEquals(str2))
}
}
@@ -1,56 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-FileCopyrightText: 2020 Tobias Kaminsky <[email protected]>
* SPDX-FileCopyrightText: 2020 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.nextcloud.ui
import androidx.annotation.UiThread
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.IdlingRegistry
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import com.owncloud.android.AbstractIT
import com.owncloud.android.lib.resources.users.Status
import com.owncloud.android.lib.resources.users.StatusType
import com.owncloud.android.ui.activity.FileDisplayActivity
import com.owncloud.android.utils.EspressoIdlingResource
import org.junit.After
import org.junit.Before
import org.junit.Test
class SetOnlineStatusBottomSheetIT : AbstractIT() {
@Before
fun registerIdlingResource() {
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
}
@After
fun unregisterIdlingResource() {
IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource)
}
@Test
@UiThread
fun open() {
launchActivity<FileDisplayActivity>().use { scenario ->
scenario.onActivity { activity ->
onIdleSync {
EspressoIdlingResource.increment()
val sut = SetOnlineStatusBottomSheet(
Status(StatusType.DND, "Working hard…", "🤖", -1)
)
sut.show(activity.supportFragmentManager, "")
EspressoIdlingResource.decrement()
onView(isRoot()).check(matches(isDisplayed()))
}
}
}
}
}
@@ -26,7 +26,7 @@ import org.junit.After
import org.junit.Before
import org.junit.Test
class SetStatusMessageBottomSheetIT : AbstractIT() {
class SetStatusDialogFragmentIT : AbstractIT() {
@Before
fun registerIdlingResource() {
IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource)
@@ -44,7 +44,7 @@ class SetStatusMessageBottomSheetIT : AbstractIT() {
scenario.onActivity { activity ->
onIdleSync {
EspressoIdlingResource.increment()
val sut = SetStatusMessageBottomSheet(
val sut = SetStatusDialogFragment.newInstance(
user,
Status(StatusType.DND, "Working hard…", "🤖", -1)
)
@@ -52,7 +52,6 @@ class SetStatusMessageBottomSheetIT : AbstractIT() {
val predefinedStatus: ArrayList<PredefinedStatus> = arrayListOf(
PredefinedStatus("meeting", "📅", "In a meeting", ClearAt("period", "3600")),
PredefinedStatus("commuting", "🚌", "Commuting", ClearAt("period", "1800")),
PredefinedStatus("be-right-back", "⏳", "Be right back", ClearAt("period", "900")),
PredefinedStatus("remote-work", "🏡", "Working remotely", ClearAt("end-of", "day")),
PredefinedStatus("sick-leave", "🤒", "Out sick", ClearAt("end-of", "day")),
PredefinedStatus("vacationing", "🌴", "Vacationing", null)
@@ -1,204 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
@Suppress("TooManyFunctions")
class FileHelperTest {
private lateinit var testDirectory: File
@Before
fun setup() {
testDirectory = Files.createTempDirectory("test").toFile()
}
@After
fun tearDown() {
testDirectory.deleteRecursively()
}
@Test
fun testListDirectoryEntriesWhenGivenNullDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(null, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenNonExistentDirectoryShouldReturnEmptyList() {
val nonExistent = File(testDirectory, "does_not_exist")
val result = FileHelper.listDirectoryEntries(nonExistent, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenFileInsteadOfDirectoryShouldReturnEmptyList() {
val file = File(testDirectory, "test.txt")
file.createNewFile()
val result = FileHelper.listDirectoryEntries(file, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenEmptyDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenFetchingFoldersShouldReturnOnlyFolders() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertEquals(2, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testListDirectoryEntriesWhenFetchingFilesShouldReturnOnlyFiles() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(2, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenStartIndexProvidedShouldSkipCorrectNumberOfItems() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(3, result.size)
}
@Test
fun testListDirectoryEntriesWhenMaxItemsProvidedShouldLimitResults() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 5, false)
assertEquals(5, result.size)
}
@Test
fun testListDirectoryEntriesWhenGivenStartIndexAndMaxItemsShouldReturnCorrectSubset() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 3, 4, false)
assertEquals(4, result.size)
}
@Test
fun testListDirectoryEntriesWhenStartIndexBeyondAvailableShouldReturnEmptyList() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 10, 5, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsBeyondAvailableShouldReturnAllItems() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 100, false)
assertEquals(3, result.size)
}
@Test
fun testListDirectoryEntriesWhenFetchingFoldersWithOffsetShouldSkipCorrectly() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, true)
assertEquals(3, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testListDirectoryEntriesWhenFetchingFilesWithOffsetShouldSkipCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(3, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenGivenOnlyFoldersAndFetchingFilesShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenOnlyFilesAndFetchingFoldersShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsIsZeroShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 0, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenMixedContentShouldFilterCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..7) File(testDirectory, "file$i.txt").createNewFile()
val folders = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
val files = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(3, folders.size)
assertEquals(7, files.size)
assertTrue(folders.all { it.isDirectory })
assertTrue(files.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenPaginatingFoldersShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "folder$i").mkdir()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 3, true)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 3, 3, true)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 6, 3, true)
val page4 = FileHelper.listDirectoryEntries(testDirectory, 9, 3, true)
assertEquals(3, page1.size)
assertEquals(3, page2.size)
assertEquals(3, page3.size)
assertEquals(1, page4.size)
}
@Test
fun testListDirectoryEntriesWhenPaginatingFilesShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 4, false)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 4, 4, false)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 8, 4, false)
assertEquals(4, page1.size)
assertEquals(4, page2.size)
assertEquals(2, page3.size)
}
}
@@ -97,12 +97,6 @@ class FileNameValidatorTests : AbstractOnServerIT() {
assertEquals(targetContext.getString(R.string.filename_empty), result)
}
@Test
fun testBlankFileName() {
val result = FileNameValidator.checkFileName(" ", capability, targetContext)
assertEquals(targetContext.getString(R.string.filename_empty), result)
}
@Test
fun testFileAlreadyExists() {
val existingFiles = setOf("existingFile")
@@ -296,7 +296,7 @@ public abstract class AbstractIT {
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
public void onIdleSync(Runnable recipient) {
protected void onIdleSync(Runnable recipient) {
InstrumentationRegistry.getInstrumentation().waitForIdle(recipient);
}
@@ -400,6 +400,11 @@ public abstract class AbstractIT {
public boolean isPowerSavingEnabled() {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
};
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
@@ -450,7 +455,7 @@ public abstract class AbstractIT {
screenshot(view, "");
}
public void screenshotViaName(Activity activity, String name) {
protected void screenshotViaName(Activity activity, String name) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
Screenshot.snapActivity(activity).setName(name).record();
}
@@ -216,6 +216,11 @@ public abstract class AbstractOnServerIT extends AbstractIT {
public boolean isPowerSavingEnabled() {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
};
UserAccountManager accountManager = UserAccountManagerImpl.fromContext(targetContext);
@@ -82,6 +82,12 @@ public class UploadIT extends AbstractOnServerIT {
public boolean isPowerSavingEnabled() {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
@NonNull
@Override
public BatteryStatus getBattery() {
@@ -231,6 +237,11 @@ public class UploadIT extends AbstractOnServerIT {
return false;
}
@Override
public boolean isPowerSavingExclusionAvailable() {
return false;
}
@NonNull
@Override
public BatteryStatus getBattery() {
@@ -43,6 +43,7 @@ class ContentResolverHelperIT {
}
@Test
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
fun contentResolver_onAndroid26_usesNewAPI() {
ContentResolverHelper
.queryResolver(resolver, URI, PROJECTION, SELECTION, null, SORT_COLUMN, SORT_DIRECTION, LIMIT)
@@ -18,7 +18,6 @@ import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.database.entity.UploadEntityKt;
import com.nextcloud.test.RandomStringGenerator;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.MainApp;
@@ -109,7 +108,7 @@ public class UploadStorageManagerTest extends AbstractIT {
OCUpload upload = createUpload(account);
uploads.add(upload);
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
uploadsStorageManager.storeUpload(upload);
}
OCUpload[] storedUploads = uploadsStorageManager.getAllStoredUploads();
@@ -152,14 +151,17 @@ public class UploadStorageManagerTest extends AbstractIT {
account.name);
corruptUpload.setLocalPath(null);
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(corruptUpload));
uploadsStorageManager.storeUpload(corruptUpload);
uploadsStorageManager.getAllStoredUploads();
}
@Test
public void getById() {
OCUpload upload = createUpload(account);
long id = uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
long id = uploadsStorageManager.storeUpload(upload);
OCUpload newUpload = uploadsStorageManager.getUploadById(id);
assertNotNull(newUpload);
@@ -176,7 +178,7 @@ public class UploadStorageManagerTest extends AbstractIT {
private void insertUploads(Account account, int rowsToInsert) {
for (int i = 0; i < rowsToInsert; i++) {
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(createUpload(account)));
uploadsStorageManager.storeUpload(createUpload(account));
}
}
@@ -1,39 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.owncloud.android.extensions
import android.app.Activity
import android.content.Intent
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.matcher.ViewMatchers.isRoot
import com.owncloud.android.AbstractIT
import com.owncloud.android.utils.EspressoIdlingResource
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
inline fun <reified T : Activity> AbstractIT.launchAndCapture(
testClassName: String,
actionName: String,
intent: Intent? = null,
crossinline before: (T) -> Unit
) {
launchActivity<T>(intent).use { scenario ->
scenario.onActivity { activity ->
onIdleSync {
EspressoIdlingResource.increment()
before(activity)
EspressoIdlingResource.decrement()
val screenshotName = createName(testClassName + "_" + actionName, "")
onView(isRoot()).check(matches(isDisplayed()))
screenshotViaName(activity, screenshotName)
}
}
}
}
@@ -46,6 +46,9 @@ abstract class FileUploaderIT : AbstractOnServerIT() {
override val isPowerSavingEnabled: Boolean
get() = false
override val isPowerSavingExclusionAvailable: Boolean
get() = false
override val battery: BatteryStatus
get() = BatteryStatus()
}
@@ -27,8 +27,8 @@ public class FileDisplayActivityTest extends AbstractIT {
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
Activity activity =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED).iterator().next();
if (activity instanceof WhatsNewActivity whatsNewActivity) {
whatsNewActivity.getOnBackPressedDispatcher().onBackPressed();
if (activity instanceof WhatsNewActivity) {
activity.onBackPressed();
}
});
scenario.recreate();
@@ -39,7 +39,6 @@ import com.nextcloud.client.account.Server
import com.nextcloud.client.device.DeviceInfo
import com.nextcloud.client.documentscan.AppScanOptionalFeature
import com.nextcloud.ui.ChooseAccountDialogFragment.Companion.newInstance
import com.nextcloud.ui.SetOnlineStatusBottomSheet
import com.nextcloud.ui.fileactions.FileActionsBottomSheet.Companion.newInstance
import com.nextcloud.utils.EditorUtils
import com.owncloud.android.AbstractIT
@@ -567,35 +566,6 @@ class DialogFragmentIT : AbstractIT() {
}
}
@Test
@UiThread
@ScreenshotTest
fun testOnlineStatusBottomSheet() {
if (Looper.myLooper() == null) {
Looper.prepare()
}
// show dialog
val intent = Intent(targetContext, FileDisplayActivity::class.java)
launchActivity<FileDisplayActivity>(intent).use { scenario ->
scenario.onActivity { fda ->
onIdleSync {
EspressoIdlingResource.increment()
val sut = SetOnlineStatusBottomSheet(
Status(StatusType.DND, "Focus time", "\uD83E\uDD13", -1)
)
EspressoIdlingResource.decrement()
sut.show(fda.supportFragmentManager, "set_online_status")
val screenShotName = createName(testClassName + "_" + "testOnlineStatusBottomSheet", "")
onView(isRoot()).check(matches(isDisplayed()))
screenshotViaName(sut.view, screenShotName)
}
}
}
}
@Test
@UiThread
@ScreenshotTest
@@ -822,7 +822,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
val processFragment =
activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG) as
FileDetailsSharingProcessFragment
processFragment.activity?.onBackPressedDispatcher?.onBackPressed()
processFragment.onBackPressed()
}
}
}
@@ -231,13 +231,6 @@ class OCFileListFragmentStaticServerIT : AbstractIT() {
sut.storageManager.saveFile(this)
}
OCFile("/Foo%e2%80%aedm.exe").apply {
remoteId = "000000011"
parentId = sut.storageManager.getFileByEncryptedRemotePath("/").fileId
modificationTimestamp = 1000
sut.storageManager.saveFile(this)
}
sut.addFragment(fragment)
val root = sut.storageManager.getFileByEncryptedRemotePath("/")
fragment.listDirectory(root, false, false)
@@ -46,7 +46,7 @@ class UnifiedSearchFragmentIT : AbstractIT() {
scenario.onActivity { activity ->
onIdleSync {
EspressoIdlingResource.increment()
val sut = UnifiedSearchFragment.newInstance(null, null, "/")
val sut = UnifiedSearchFragment.newInstance(null, null)
activity.addFragment(sut)
sut.onSearchResultChanged(
@@ -83,7 +83,7 @@ class UnifiedSearchFragmentIT : AbstractIT() {
onIdleSync {
EspressoIdlingResource.increment()
val sut = UnifiedSearchFragment.newInstance(null, null, "/")
val sut = UnifiedSearchFragment.newInstance(null, null)
val testViewModel = UnifiedSearchViewModel(activity.application)
testViewModel.setConnectivityService(activity.connectivityServiceMock)
val localRepository = UnifiedSearchFakeRepository()
@@ -20,7 +20,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isRoot
import com.owncloud.android.utils.EspressoIdlingResource
import com.owncloud.android.AbstractIT
import com.owncloud.android.MainApp
import com.owncloud.android.extensions.launchAndCapture
import com.owncloud.android.lib.common.accounts.AccountUtils
import com.owncloud.android.utils.ScreenshotTest
import org.junit.After
@@ -72,50 +71,84 @@ class TrashbinActivityIT : AbstractIT() {
@UiThread
@ScreenshotTest
fun files() {
launchAndCapture<TrashbinActivity>(testClassName, "files", before = { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.FILES)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.loadFolder(
onComplete = { EspressoIdlingResource.decrement() },
onError = { EspressoIdlingResource.decrement() }
)
})
launchActivity<TrashbinActivity>().use { scenario ->
scenario.onActivity { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.FILES)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
onIdleSync {
EspressoIdlingResource.increment()
sut.loadFolder(
onComplete = { EspressoIdlingResource.decrement() },
onError = { EspressoIdlingResource.decrement() }
)
onView(isRoot()).check(matches(isDisplayed()))
val screenShotName = createName(testClassName + "_" + "files", "")
screenshotViaName(sut, screenShotName)
}
}
}
}
@Test
@UiThread
@ScreenshotTest
fun empty() {
launchAndCapture<TrashbinActivity>(testClassName, "empty", before = { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.loadFolder(
onComplete = { EspressoIdlingResource.decrement() },
onError = { EspressoIdlingResource.decrement() }
)
})
launchActivity<TrashbinActivity>().use { scenario ->
scenario.onActivity { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
onIdleSync {
EspressoIdlingResource.increment()
sut.loadFolder(
onComplete = { EspressoIdlingResource.decrement() },
onError = { EspressoIdlingResource.decrement() }
)
onView(isRoot()).check(matches(isDisplayed()))
val screenShotName = createName(testClassName + "_" + "empty", "")
screenshotViaName(sut, screenShotName)
}
}
}
}
@Test
@UiThread
@ScreenshotTest
fun loading() {
launchAndCapture<TrashbinActivity>(testClassName, "loading", before = { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.showInitialLoading()
})
launchActivity<TrashbinActivity>().use { scenario ->
scenario.onActivity { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
onIdleSync {
EspressoIdlingResource.increment()
sut.showInitialLoading()
EspressoIdlingResource.decrement()
val screenShotName = createName(testClassName + "_" + "loading", "")
onView(isRoot()).check(matches(isDisplayed()))
screenshotViaName(sut, screenShotName)
}
}
}
}
@Test
@UiThread
@ScreenshotTest
fun normalUser() {
launchAndCapture<TrashbinActivity>(testClassName, "normalUser", before = { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.showUser()
})
launchActivity<TrashbinActivity>().use { scenario ->
scenario.onActivity { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
onIdleSync {
EspressoIdlingResource.increment()
sut.showUser()
EspressoIdlingResource.decrement()
val screenShotName = createName(testClassName + "_" + "normalUser", "")
onView(isRoot()).check(matches(isDisplayed()))
screenshotViaName(sut, screenShotName)
}
}
}
}
@Test
@@ -134,10 +167,19 @@ class TrashbinActivityIT : AbstractIT() {
putExtra(Intent.EXTRA_USER, "differentUser@https://nextcloud.localhost")
}
launchAndCapture<TrashbinActivity>(testClassName, "differentUser", intent = intent, before = { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
sut.showUser()
})
launchActivity<TrashbinActivity>(intent).use { scenario ->
scenario.onActivity { sut ->
val trashbinRepository = TrashbinLocalRepository(TestCase.EMPTY)
sut.trashbinPresenter = TrashbinPresenter(trashbinRepository, sut)
onIdleSync {
EspressoIdlingResource.increment()
sut.showUser()
EspressoIdlingResource.decrement()
val screenShotName = createName(testClassName + "_" + "differentUser", "")
onView(isRoot()).check(matches(isDisplayed()))
screenshotViaName(sut, screenShotName)
}
}
}
}
}
@@ -30,6 +30,8 @@ class CapabilityUtilsIT : AbstractIT() {
assertTrue(test(NextcloudVersion.nextcloud_22))
assertTrue(test(NextcloudVersion.nextcloud_21))
assertTrue(test(OwnCloudVersion.nextcloud_20))
assertTrue(test(OwnCloudVersion.nextcloud_19))
assertTrue(test(OwnCloudVersion.nextcloud_18))
}
private fun test(version: OwnCloudVersion): Boolean =
@@ -44,7 +44,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
+3 -8
View File
@@ -121,7 +121,7 @@
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:enableOnBackInvokedCallback="false"
android:theme="@style/Theme.ownCloud.Toolbar"
android:usesCleartextTraffic="true"
tools:ignore="UnusedAttribute"
@@ -269,9 +269,6 @@
android:exported="false"
tools:replace="android:exported" />
<receiver
android:name="com.nextcloud.client.jobs.offlineOperations.receiver.OfflineOperationReceiver"
android:exported="false" />
<receiver
android:name=".operations.upload.UploadFileBroadcastReceiver"
android:exported="false" />
@@ -353,7 +350,6 @@
<activity
android:name=".ui.activity.SettingsActivity"
android:exported="false"
android:enableOnBackInvokedCallback="false"
android:theme="@style/PreferenceTheme" />
<activity
android:name=".ui.preview.PreviewImageActivity"
@@ -585,8 +581,6 @@
</intent-filter>
</receiver>
<receiver android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver" android:exported="false" />
<activity
android:name=".ui.activity.CopyToClipboardActivity"
android:exported="false"
@@ -619,7 +613,8 @@
<activity
android:name=".ui.activity.ManageSpaceActivity"
android:exported="false"
android:label="@string/manage_space_title" />
android:label="@string/manage_space_title"
android:theme="@style/Theme.ownCloud" />
<service
android:name=".services.AccountManagerService"
@@ -9,12 +9,28 @@
*/
package com.nextcloud.android.sso;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.util.EncodingUtil;
import java.util.Vector;
public class PatchMethod extends PostMethod {
/**
* The buffered request body consisting of <code>NameValuePair</code>s.
*/
private Vector params = new Vector();
/**
* No-arg constructor.
*/
public PatchMethod() {
super();
}
/**
* Constructor specifying a URI.
*
@@ -42,7 +58,11 @@ public class PatchMethod extends PostMethod {
* @since 2.0beta1
*/
protected boolean hasRequestContent() {
return super.hasRequestContent();
if (!this.params.isEmpty()) {
return true;
} else {
return super.hasRequestContent();
}
}
/**
@@ -51,6 +71,7 @@ public class PatchMethod extends PostMethod {
* @since 2.0beta1
*/
protected void clearRequestBody() {
this.params.clear();
super.clearRequestBody();
}
@@ -61,6 +82,19 @@ public class PatchMethod extends PostMethod {
* @since 3.0
*/
protected RequestEntity generateRequestEntity() {
return super.generateRequestEntity();
if (!this.params.isEmpty()) {
// Use a ByteArrayRequestEntity instead of a StringRequestEntity.
// This is to avoid potential encoding issues. Form url encoded strings
// are ASCII by definition but the content type may not be. Treating the content
// as bytes allows us to keep the current charset without worrying about how
// this charset will effect the encoding of the form url encoded string.
String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
return new ByteArrayRequestEntity(
EncodingUtil.getAsciiBytes(content),
FORM_URL_ENCODED_CONTENT_TYPE
);
} else {
return super.generateRequestEntity();
}
}
}
@@ -17,10 +17,7 @@ import com.nextcloud.client.core.Clock
import com.nextcloud.client.core.ClockImpl
import com.nextcloud.client.database.dao.ArbitraryDataDao
import com.nextcloud.client.database.dao.FileDao
import com.nextcloud.client.database.dao.FileSystemDao
import com.nextcloud.client.database.dao.OfflineOperationDao
import com.nextcloud.client.database.dao.RecommendedFileDao
import com.nextcloud.client.database.dao.SyncedFolderDao
import com.nextcloud.client.database.dao.UploadDao
import com.nextcloud.client.database.entity.ArbitraryDataEntity
import com.nextcloud.client.database.entity.CapabilityEntity
@@ -28,7 +25,6 @@ import com.nextcloud.client.database.entity.ExternalLinkEntity
import com.nextcloud.client.database.entity.FileEntity
import com.nextcloud.client.database.entity.FilesystemEntity
import com.nextcloud.client.database.entity.OfflineOperationEntity
import com.nextcloud.client.database.entity.RecommendedFileEntity
import com.nextcloud.client.database.entity.ShareEntity
import com.nextcloud.client.database.entity.SyncedFolderEntity
import com.nextcloud.client.database.entity.UploadEntity
@@ -52,8 +48,7 @@ import com.owncloud.android.db.ProviderMeta
SyncedFolderEntity::class,
UploadEntity::class,
VirtualEntity::class,
OfflineOperationEntity::class,
RecommendedFileEntity::class
OfflineOperationEntity::class
],
version = ProviderMeta.DB_VERSION,
autoMigrations = [
@@ -80,10 +75,7 @@ import com.owncloud.android.db.ProviderMeta
AutoMigration(from = 86, to = 87, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
AutoMigration(from = 87, to = 88, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class),
// manual migration used for 88 to 89
AutoMigration(from = 89, to = 90),
AutoMigration(from = 90, to = 91),
AutoMigration(from = 91, to = 92),
AutoMigration(from = 92, to = 93, spec = DatabaseMigrationUtil.ResetCapabilitiesPostMigration::class)
AutoMigration(from = 89, to = 90)
],
exportSchema = true
)
@@ -95,9 +87,6 @@ abstract class NextcloudDatabase : RoomDatabase() {
abstract fun fileDao(): FileDao
abstract fun offlineOperationDao(): OfflineOperationDao
abstract fun uploadDao(): UploadDao
abstract fun recommendedFileDao(): RecommendedFileDao
abstract fun fileSystemDao(): FileSystemDao
abstract fun syncedFolderDao(): SyncedFolderDao
companion object {
const val FIRST_ROOM_DB_VERSION = 65
@@ -12,9 +12,7 @@ import androidx.room.Query
import androidx.room.Update
import com.nextcloud.client.database.entity.FileEntity
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
import com.owncloud.android.utils.MimeType
@Suppress("TooManyFunctions")
@Dao
interface FileDao {
@Update
@@ -64,51 +62,4 @@ interface FileDao {
"ORDER BY internal_two_way_sync_timestamp DESC"
)
fun getInternalTwoWaySyncFolders(fileOwner: String): List<FileEntity>
@Query(
"""
SELECT *
FROM filelist
WHERE parent = :parentId
AND file_owner = :accountName
AND is_encrypted = 0
AND (content_type = :dirType OR content_type = :webdavType)
ORDER BY ${ProviderTableMeta.FILE_DEFAULT_SORT_ORDER}
"""
)
fun getNonEncryptedSubfolders(
parentId: Long,
accountName: String,
dirType: String = MimeType.DIRECTORY,
webdavType: String = MimeType.WEBDAV_FOLDER
): List<FileEntity>
@Query(
"""
SELECT *
FROM filelist
WHERE parent = :parentId
AND file_owner = :accountName
AND (content_type != :dirType AND content_type != :webdavType)
ORDER BY ${ProviderTableMeta.FILE_DEFAULT_SORT_ORDER}
"""
)
fun getSubfiles(
parentId: Long,
accountName: String,
dirType: String = MimeType.DIRECTORY,
webdavType: String = MimeType.WEBDAV_FOLDER
): List<FileEntity>
@Query(
"""
SELECT *
FROM filelist
WHERE file_owner = :fileOwner
AND parent = :parentId
AND ${ProviderTableMeta.FILE_NAME} LIKE '%' || :query || '%'
ORDER BY ${ProviderTableMeta.FILE_DEFAULT_SORT_ORDER}
"""
)
fun searchFilesInFolder(parentId: Long, fileOwner: String, query: String): List<FileEntity>
}
@@ -1,40 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.database.dao
import androidx.room.Dao
import androidx.room.Query
import com.nextcloud.client.database.entity.FilesystemEntity
import com.owncloud.android.db.ProviderMeta
@Dao
interface FileSystemDao {
@Query(
"""
SELECT *
FROM ${ProviderMeta.ProviderTableMeta.FILESYSTEM_TABLE_NAME}
WHERE ${ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID} = :syncedFolderId
AND ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD} = 0
AND ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER} = 0
AND ${ProviderMeta.ProviderTableMeta._ID} > :lastId
ORDER BY ${ProviderMeta.ProviderTableMeta._ID}
LIMIT :limit
"""
)
suspend fun getAutoUploadFilesEntities(syncedFolderId: String, limit: Int, lastId: Int): List<FilesystemEntity>
@Query(
"""
UPDATE ${ProviderMeta.ProviderTableMeta.FILESYSTEM_TABLE_NAME}
SET ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD} = 1
WHERE ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH} = :localPath
AND ${ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID} = :syncedFolderId
"""
)
suspend fun markFileAsUploaded(localPath: String, syncedFolderId: String)
}
@@ -40,7 +40,4 @@ interface OfflineOperationDao {
@Query("DELETE FROM offline_operations")
fun clearTable()
@Query("DELETE FROM offline_operations WHERE _id = :id")
fun deleteById(id: Int)
}
@@ -1,26 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.nextcloud.client.database.entity.RecommendedFileEntity
import com.owncloud.android.db.ProviderMeta
@Dao
interface RecommendedFileDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(recommendedFiles: List<RecommendedFileEntity>)
@Query(
"SELECT * FROM ${ProviderMeta.ProviderTableMeta.RECOMMENDED_FILE_TABLE_NAME} WHERE account_name = :accountName"
)
suspend fun getAll(accountName: String): List<RecommendedFileEntity>
}
@@ -1,26 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.database.dao
import androidx.room.Dao
import androidx.room.Query
import com.nextcloud.client.database.entity.SyncedFolderEntity
import com.owncloud.android.db.ProviderMeta
@Dao
interface SyncedFolderDao {
@Query(
"""
SELECT * FROM ${ProviderMeta.ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME}
WHERE ${ProviderMeta.ProviderTableMeta.SYNCED_FOLDER_LOCAL_PATH} = :localPath
AND ${ProviderMeta.ProviderTableMeta.SYNCED_FOLDER_ACCOUNT} = :account
LIMIT 1
"""
)
fun findByLocalPathAndAccount(localPath: String, account: String): SyncedFolderEntity?
}
@@ -8,10 +8,7 @@
package com.nextcloud.client.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.nextcloud.client.database.entity.UploadEntity
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Dao
@@ -22,59 +19,4 @@ interface UploadDao {
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " = :accountName AND _id IS NOT NULL"
)
fun getAllIds(status: Int, accountName: String): List<Int>
@Query(
"SELECT * FROM " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" WHERE " + ProviderTableMeta._ID + " IN (:ids) AND " +
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " = :accountName"
)
fun getUploadsByIds(ids: LongArray, accountName: String): List<UploadEntity>
@Query(
"SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME} " +
"WHERE ${ProviderTableMeta.UPLOADS_REMOTE_PATH} = :remotePath LIMIT 1"
)
fun getByRemotePath(remotePath: String): UploadEntity?
@Query(
"DELETE FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME} " +
"WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName " +
"AND ${ProviderTableMeta.UPLOADS_REMOTE_PATH} = :remotePath"
)
fun deleteByAccountAndRemotePath(accountName: String, remotePath: String)
@Query(
"SELECT * FROM " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" WHERE " + ProviderTableMeta._ID + " = :id AND " +
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " = :accountName " +
"LIMIT 1"
)
fun getUploadById(id: Long, accountName: String): UploadEntity?
@Insert(onConflict = OnConflictStrategy.Companion.REPLACE)
fun insertOrReplace(entity: UploadEntity): Long
@Query(
"SELECT * FROM " + ProviderTableMeta.UPLOADS_TABLE_NAME +
" WHERE " + ProviderTableMeta.UPLOADS_ACCOUNT_NAME + " = :accountName AND " +
ProviderTableMeta.UPLOADS_LOCAL_PATH + " = :localPath AND " +
ProviderTableMeta.UPLOADS_REMOTE_PATH + " = :remotePath " +
"LIMIT 1"
)
fun getUploadByAccountAndPaths(accountName: String, localPath: String, remotePath: String): UploadEntity?
@Query(
"UPDATE ${ProviderTableMeta.UPLOADS_TABLE_NAME} " +
"SET ${ProviderTableMeta.UPLOADS_STATUS} = :status " +
"WHERE ${ProviderTableMeta.UPLOADS_REMOTE_PATH} = :remotePath " +
"AND ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName"
)
suspend fun updateStatus(remotePath: String, accountName: String, status: Int): Int
@Query(
"SELECT * FROM ${ProviderTableMeta.UPLOADS_TABLE_NAME} " +
"WHERE ${ProviderTableMeta.UPLOADS_ACCOUNT_NAME} = :accountName " +
"AND ${ProviderTableMeta.UPLOADS_STATUS} = :status"
)
suspend fun getUploadsByStatus(accountName: String, status: Int): List<UploadEntity>
}
@@ -140,7 +140,5 @@ data class CapabilityEntity(
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_NOTES_FOLDER_PATH)
val notesFolderPath: String?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_DEFAULT_PERMISSIONS)
val defaultPermissions: Int?,
@ColumnInfo(name = ProviderTableMeta.CAPABILITIES_USER_STATUS_SUPPORTS_BUSY)
val userStatusSupportsBusy: Int?
val defaultPermissions: Int?
)
@@ -42,27 +42,13 @@ data class OfflineOperationEntity(
fun isRenameOrRemove(): Boolean =
(type is OfflineOperationType.RenameFile || type is OfflineOperationType.RemoveFile)
fun isCreate(): Boolean = (type is OfflineOperationType.CreateFile || type is OfflineOperationType.CreateFolder)
fun getConflictText(context: Context): String {
val resId = when (type) {
is OfflineOperationType.RemoveFile -> {
R.string.offline_operations_worker_notification_remove_conflict_text
}
is OfflineOperationType.RenameFile -> {
R.string.offline_operations_worker_notification_rename_conflict_text
}
is OfflineOperationType.CreateFile -> {
R.string.offline_operations_worker_notification_create_file_conflict_text
}
else -> {
R.string.offline_operations_worker_notification_create_folder_conflict_text
}
}
return context.getString(resId, filename)
fun getConflictText(context: Context): String = if (type is OfflineOperationType.RemoveFile) {
context.getString(R.string.offline_operations_worker_notification_remove_conflict_text, filename)
} else if (type is OfflineOperationType.RenameFile) {
context.getString(R.string.offline_operations_worker_notification_rename_conflict_text, filename)
} else if (type is OfflineOperationType.CreateFile) {
context.getString(R.string.offline_operations_worker_notification_create_file_conflict_text, filename)
} else {
context.getString(R.string.offline_operations_worker_notification_create_folder_conflict_text, filename)
}
}
@@ -1,72 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.nextcloud.android.lib.resources.recommendations.Recommendation
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.RECOMMENDED_FILE_TABLE_NAME)
data class RecommendedFileEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
val id: Long,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_NAME)
val name: String,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_DIRECTORY)
val directory: String,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_EXTENSIONS)
val extension: String,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_MIME_TYPE)
val mimeType: String,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_HAS_PREVIEW)
val hasPreview: Boolean,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_REASON)
val reason: String,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_TIMESTAMP)
val timestamp: Long,
@ColumnInfo(name = ProviderTableMeta.RECOMMENDED_FILE_ACCOUNT_NAME)
val accountName: String?
)
fun ArrayList<Recommendation>.toEntity(accountName: String): List<RecommendedFileEntity> = this.map { recommendation ->
RecommendedFileEntity(
id = recommendation.id,
name = recommendation.name,
directory = recommendation.directory,
extension = recommendation.extension,
mimeType = recommendation.mimeType,
hasPreview = recommendation.hasPreview,
reason = recommendation.reason,
timestamp = recommendation.timestamp,
accountName = accountName
)
}
fun List<RecommendedFileEntity>.toOCFile(storageManager: FileDataStorageManager): ArrayList<OCFile> =
mapNotNull { entity ->
entity.id.let {
storageManager.getFileByLocalId(it).apply {
this?.reason = entity.reason
this?.setIsRecommendedFile(true)
}
}
}
.toCollection(ArrayList())
@@ -10,9 +10,6 @@ package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.nextcloud.client.preferences.SubFolderRule
import com.owncloud.android.datamodel.MediaFolderType
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME)
@@ -53,40 +50,3 @@ data class SyncedFolderEntity(
@ColumnInfo(name = ProviderTableMeta.SYNCED_FOLDER_LAST_SCAN_TIMESTAMP_MS)
val lastScanTimestampMs: Long?
)
fun SyncedFolderEntity.toSyncedFolder(): SyncedFolder = SyncedFolder(
// id
(this.id ?: SyncedFolder.UNPERSISTED_ID).toLong(),
// localPath
this.localPath ?: "",
// remotePath
this.remotePath ?: "",
// wifiOnly
this.wifiOnly == 1,
// chargingOnly
this.chargingOnly == 1,
// existing
this.existing == 1,
// subfolderByDate
this.subfolderByDate == 1,
// account
this.account ?: "",
// uploadAction
this.uploadAction ?: 0,
// nameCollisionPolicy
this.nameCollisionPolicy ?: 0,
// enabled
this.enabled == 1,
// timestampMs
(this.enabledTimestampMs ?: SyncedFolder.EMPTY_ENABLED_TIMESTAMP_MS).toLong(),
// type
MediaFolderType.getById(this.type ?: MediaFolderType.CUSTOM.id),
// hidden
this.hidden == 1,
// subFolderRule
this.subFolderRule?.let { SubFolderRule.entries[it] },
// excludeHidden
this.excludeHidden == 1,
// lastScanTimestampMs
this.lastScanTimestampMs ?: SyncedFolder.NOT_SCANNED_YET
)
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2022 Álvaro Brey <alvaro@alvarobrey.com>
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
@@ -11,13 +10,7 @@ package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.nextcloud.utils.autoRename.AutoRename
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
import com.owncloud.android.db.UploadResult
import com.owncloud.android.files.services.NameCollisionPolicy
import com.owncloud.android.lib.resources.status.OCCapability
@Entity(tableName = ProviderTableMeta.UPLOADS_TABLE_NAME)
data class UploadEntity(
@@ -55,57 +48,3 @@ data class UploadEntity(
@ColumnInfo(name = ProviderTableMeta.UPLOADS_FOLDER_UNLOCK_TOKEN)
val folderUnlockToken: String?
)
fun UploadEntity.toOCUpload(capability: OCCapability? = null): OCUpload {
val localPath = localPath
var remotePath = remotePath
if (capability != null && remotePath != null) {
remotePath = AutoRename.rename(remotePath, capability)
}
val upload = OCUpload(localPath, remotePath, accountName)
fileSize?.let { upload.fileSize = it }
id?.let { upload.uploadId = it.toLong() }
status?.let { upload.uploadStatus = UploadsStorageManager.UploadStatus.fromValue(it) }
localBehaviour?.let { upload.localAction = it }
nameCollisionPolicy?.let { upload.nameCollisionPolicy = NameCollisionPolicy.deserialize(it) }
isCreateRemoteFolder?.let { upload.isCreateRemoteFolder = it == 1 }
uploadEndTimestamp?.let { upload.uploadEndTimestamp = it.toLong() }
lastResult?.let { upload.lastResult = UploadResult.fromValue(it) }
createdBy?.let { upload.createdBy = it }
isWifiOnly?.let { upload.isUseWifiOnly = it == 1 }
isWhileChargingOnly?.let { upload.isWhileChargingOnly = it == 1 }
folderUnlockToken?.let { upload.folderUnlockToken = it }
return upload
}
fun OCUpload.toUploadEntity(): UploadEntity {
val id = if (uploadId == -1L) {
// needed for the insert new records to the db so that insert DAO function returns new generated id
null
} else {
uploadId
}
return UploadEntity(
id = id?.toInt(),
localPath = localPath,
remotePath = remotePath,
accountName = accountName,
fileSize = fileSize,
status = uploadStatus?.value,
localBehaviour = localAction,
nameCollisionPolicy = nameCollisionPolicy?.serialize(),
isCreateRemoteFolder = if (isCreateRemoteFolder) 1 else 0,
// uploadEndTimestamp may overflow max int capacity since it is conversion from long to int. coerceAtMost needed
uploadEndTimestamp = uploadEndTimestamp.coerceAtMost(Int.MAX_VALUE.toLong()).toInt(),
lastResult = lastResult?.value,
createdBy = createdBy,
isWifiOnly = if (isUseWifiOnly) 1 else 0,
isWhileChargingOnly = if (isWhileChargingOnly) 1 else 0,
folderUnlockToken = folderUnlockToken,
uploadTime = null
)
}
@@ -10,6 +10,7 @@ package com.nextcloud.client.device
import android.content.Context
import android.os.PowerManager
import com.nextcloud.client.preferences.AppPreferences
import dagger.Module
import dagger.Provides
@@ -17,11 +18,13 @@ import dagger.Provides
class DeviceModule {
@Provides
fun powerManagementService(context: Context): PowerManagementService {
fun powerManagementService(context: Context, preferences: AppPreferences): PowerManagementService {
val platformPowerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return PowerManagementServiceImpl(
context = context,
platformPowerManager = platformPowerManager
platformPowerManager = platformPowerManager,
deviceInfo = DeviceInfo(),
preferences = preferences
)
}
}
@@ -21,6 +21,14 @@ interface PowerManagementService {
*/
val isPowerSavingEnabled: Boolean
/**
* Checks if the device vendor requires power saving
* exclusion workaround.
*
* @return true if workaround is required, false otherwise
*/
val isPowerSavingExclusionAvailable: Boolean
/**
* Checks current battery status using platform [android.os.BatteryManager]
*/
@@ -11,27 +11,46 @@ import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.PowerManager
import com.nextcloud.client.preferences.AppPreferences
import com.nextcloud.client.preferences.AppPreferencesImpl
import com.nextcloud.utils.extensions.registerBroadcastReceiver
import com.owncloud.android.datamodel.ReceiverFlag
internal class PowerManagementServiceImpl(
private val context: Context,
private val platformPowerManager: PowerManager
private val platformPowerManager: PowerManager,
private val preferences: AppPreferences,
private val deviceInfo: DeviceInfo = DeviceInfo()
) : PowerManagementService {
companion object {
/**
* Vendors on this list use aggressive power saving methods that might
* break application experience.
*/
val OVERLY_AGGRESSIVE_POWER_SAVING_VENDORS = setOf("samsung", "huawei", "xiaomi")
@JvmStatic
fun fromContext(context: Context): PowerManagementServiceImpl {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return PowerManagementServiceImpl(context, powerManager)
val preferences = AppPreferencesImpl.fromContext(context)
return PowerManagementServiceImpl(context, powerManager, preferences, DeviceInfo())
}
}
override val isPowerSavingEnabled: Boolean
get() {
if (preferences.isPowerCheckDisabled) {
return false
}
return platformPowerManager.isPowerSaveMode
}
override val isPowerSavingExclusionAvailable: Boolean
get() = deviceInfo.vendor in OVERLY_AGGRESSIVE_POWER_SAVING_VENDORS
@Suppress("MagicNumber") // 100% is 100, we're not doing Cobol
override val battery: BatteryStatus
get() {
@@ -16,8 +16,6 @@ import com.nextcloud.client.device.DeviceModule;
import com.nextcloud.client.integrations.IntegrationsModule;
import com.nextcloud.client.jobs.JobsModule;
import com.nextcloud.client.jobs.download.FileDownloadHelper;
import com.nextcloud.client.jobs.offlineOperations.receiver.OfflineOperationReceiver;
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver;
import com.nextcloud.client.jobs.upload.FileUploadBroadcastReceiver;
import com.nextcloud.client.jobs.upload.FileUploadHelper;
import com.nextcloud.client.media.BackgroundPlayerService;
@@ -74,10 +72,6 @@ public interface AppComponent {
void inject(FileUploadBroadcastReceiver fileUploadBroadcastReceiver);
void inject(OfflineOperationReceiver offlineOperationReceiver);
void inject(FolderDownloadWorkerReceiver folderDownloadWorkerReceiver);
@Component.Builder
interface Builder {
@BindsInstance
@@ -30,8 +30,7 @@ import com.nextcloud.receiver.NetworkChangeReceiver;
import com.nextcloud.ui.ChooseAccountDialogFragment;
import com.nextcloud.ui.ChooseStorageLocationDialogFragment;
import com.nextcloud.ui.ImageDetailFragment;
import com.nextcloud.ui.SetOnlineStatusBottomSheet;
import com.nextcloud.ui.SetStatusMessageBottomSheet;
import com.nextcloud.ui.SetStatusDialogFragment;
import com.nextcloud.ui.composeActivity.ComposeActivity;
import com.nextcloud.ui.fileactions.FileActionsBottomSheet;
import com.nextcloud.ui.trashbinFileActions.TrashbinFileActionsBottomSheet;
@@ -90,6 +89,7 @@ import com.owncloud.android.ui.dialog.LocalStoragePathPickerDialogFragment;
import com.owncloud.android.ui.dialog.MultipleAccountsDialog;
import com.owncloud.android.ui.dialog.RemoveFilesDialogFragment;
import com.owncloud.android.ui.dialog.RenameFileDialogFragment;
import com.owncloud.android.ui.dialog.RenamePublicShareDialogFragment;
import com.owncloud.android.ui.dialog.SendFilesDialog;
import com.owncloud.android.ui.dialog.SendShareDialog;
import com.owncloud.android.ui.dialog.SharePasswordDialogFragment;
@@ -301,7 +301,7 @@ abstract class ComponentsModule {
abstract ChooseAccountDialogFragment chooseAccountDialogFragment();
@ContributesAndroidInjector
abstract SetOnlineStatusBottomSheet setOnlineStatusBottomSheet();
abstract SetStatusDialogFragment setStatusDialogFragment();
@ContributesAndroidInjector
abstract PreviewTextFileFragment previewTextFileFragment();
@@ -414,6 +414,9 @@ abstract class ComponentsModule {
@ContributesAndroidInjector
abstract RemoveFilesDialogFragment removeFilesDialogFragment();
@ContributesAndroidInjector
abstract RenamePublicShareDialogFragment renamePublicShareDialogFragment();
@ContributesAndroidInjector
abstract SendShareDialog sendShareDialog();
@@ -502,7 +505,4 @@ abstract class ComponentsModule {
@ContributesAndroidInjector
abstract TermsOfServiceDialog termsOfServiceDialog();
@ContributesAndroidInjector
abstract SetStatusMessageBottomSheet setStatusMessageBottomSheet();
}
@@ -104,7 +104,7 @@ class DocumentScanActivity :
true
}
android.R.id.home -> {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
true
}
else -> false
@@ -10,7 +10,6 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.nextcloud.client.di.Injectable
@@ -47,7 +46,6 @@ class EtmActivity :
onPageChanged(it)
}
)
handleOnBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
@@ -60,17 +58,11 @@ class EtmActivity :
else -> super.onOptionsItemSelected(item)
}
private fun handleOnBackPressed() {
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val handledByVm = vm.onBackPressed()
if (!handledByVm) {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
})
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (!vm.onBackPressed()) {
super.onBackPressed()
}
}
private fun onPageChanged(page: EtmMenuEntry?) {
@@ -17,17 +17,13 @@ import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.core.Clock
import com.nextcloud.client.database.NextcloudDatabase
import com.nextcloud.client.device.DeviceInfo
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.documentscan.GeneratePDFUseCase
import com.nextcloud.client.documentscan.GeneratePdfFromImagesWork
import com.nextcloud.client.integrations.deck.DeckApi
import com.nextcloud.client.jobs.autoUpload.AutoUploadWorker
import com.nextcloud.client.jobs.autoUpload.FileSystemRepository
import com.nextcloud.client.jobs.download.FileDownloadWorker
import com.nextcloud.client.jobs.metadata.MetadataWorker
import com.nextcloud.client.jobs.offlineOperations.OfflineOperationsWorker
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.client.logger.Logger
import com.nextcloud.client.network.ConnectivityService
@@ -53,6 +49,7 @@ class BackgroundJobFactory @Inject constructor(
private val clock: Clock,
private val powerManagementService: PowerManagementService,
private val backgroundJobManager: Provider<BackgroundJobManager>,
private val deviceInfo: DeviceInfo,
private val accountManager: UserAccountManager,
private val resources: Resources,
private val arbitraryDataProvider: ArbitraryDataProvider,
@@ -64,8 +61,7 @@ class BackgroundJobFactory @Inject constructor(
private val viewThemeUtils: Provider<ViewThemeUtils>,
private val localBroadcastManager: Provider<LocalBroadcastManager>,
private val generatePdfUseCase: GeneratePDFUseCase,
private val syncedFolderProvider: SyncedFolderProvider,
private val database: NextcloudDatabase
private val syncedFolderProvider: SyncedFolderProvider
) : WorkerFactory() {
@SuppressLint("NewApi")
@@ -87,7 +83,7 @@ class BackgroundJobFactory @Inject constructor(
when (workerClass) {
ContactsBackupWork::class -> createContactsBackupWork(context, workerParameters)
ContactsImportWork::class -> createContactsImportWork(context, workerParameters)
AutoUploadWorker::class -> createFilesSyncWork(context, workerParameters)
FilesSyncWork::class -> createFilesSyncWork(context, workerParameters)
OfflineSyncWork::class -> createOfflineSyncWork(context, workerParameters)
MediaFoldersDetectionWork::class -> createMediaFoldersDetectionWork(context, workerParameters)
NotificationWork::class -> createNotificationWork(context, workerParameters)
@@ -102,8 +98,6 @@ class BackgroundJobFactory @Inject constructor(
TestJob::class -> createTestJob(context, workerParameters)
OfflineOperationsWorker::class -> createOfflineOperationsWorker(context, workerParameters)
InternalTwoWaySyncWork::class -> createInternalTwoWaySyncWork(context, workerParameters)
MetadataWorker::class -> createMetadataWorker(context, workerParameters)
FolderDownloadWorker::class -> createFolderDownloadWorker(context, workerParameters)
else -> null // caller falls back to default factory
}
}
@@ -170,16 +164,16 @@ class BackgroundJobFactory @Inject constructor(
contentResolver
)
private fun createFilesSyncWork(context: Context, params: WorkerParameters): AutoUploadWorker = AutoUploadWorker(
private fun createFilesSyncWork(context: Context, params: WorkerParameters): FilesSyncWork = FilesSyncWork(
context = context,
params = params,
contentResolver = contentResolver,
userAccountManager = accountManager,
uploadsStorageManager = uploadsStorageManager,
connectivityService = connectivityService,
powerManagementService = powerManagementService,
syncedFolderProvider = syncedFolderProvider,
backgroundJobManager = backgroundJobManager.get(),
repository = FileSystemRepository(dao = database.fileSystemDao())
backgroundJobManager = backgroundJobManager.get()
)
private fun createOfflineSyncWork(context: Context, params: WorkerParameters): OfflineSyncWork = OfflineSyncWork(
@@ -283,18 +277,4 @@ class BackgroundJobFactory @Inject constructor(
connectivityService,
preferences
)
private fun createMetadataWorker(context: Context, params: WorkerParameters): MetadataWorker = MetadataWorker(
context,
params,
accountManager.user
)
private fun createFolderDownloadWorker(context: Context, params: WorkerParameters): FolderDownloadWorker =
FolderDownloadWorker(
accountManager,
context,
viewThemeUtils.get(),
params
)
}
@@ -10,7 +10,6 @@ import androidx.lifecycle.LiveData
import androidx.work.ListenableWorker
import com.nextcloud.client.account.User
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.operations.DownloadType
/**
@@ -120,12 +119,15 @@ interface BackgroundJobManager {
fun startImmediateFilesExportJob(files: Collection<OCFile>): LiveData<JobInfo?>
fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder)
fun schedulePeriodicFilesSyncJob(syncedFolderID: Long)
fun startAutoUploadImmediately(
syncedFolder: SyncedFolder,
/**
* Immediately start File Sync job for given syncFolderID.
*/
fun startImmediateFilesSyncJob(
syncedFolderID: Long,
overridePowerSaving: Boolean = false,
contentUris: Array<String?> = arrayOf()
changedFiles: Array<String?> = arrayOf<String?>()
)
fun cancelTwoWaySyncJob()
@@ -137,13 +139,15 @@ interface BackgroundJobManager {
fun startNotificationJob(subject: String, signature: String)
fun startAccountRemovalJob(accountName: String, remoteWipe: Boolean)
fun startFilesUploadJob(user: User, uploadIds: LongArray, showSameFileAlreadyExistsNotification: Boolean)
fun startFilesUploadJob(user: User, uploadIds: LongArray, isAutoUpload: Boolean = false)
fun getFileUploads(user: User): LiveData<List<JobInfo>>
fun cancelFilesUploadJob(user: User)
fun isStartFileUploadJobScheduled(accountName: String): Boolean
fun isStartFileUploadJobScheduled(user: User): Boolean
fun cancelFilesDownloadJob(user: User, fileId: Long)
fun isStartFileDownloadJobScheduled(user: User, fileId: Long): Boolean
@Suppress("LongParameterList")
fun startFileDownloadJob(
user: User,
@@ -170,7 +174,4 @@ interface BackgroundJobManager {
fun startPeriodicallyOfflineOperation()
fun scheduleInternal2WaySync(intervalMinutes: Long)
fun cancelAllFilesDownloadJobs()
fun startMetadataSyncJob(currentDirPath: String)
fun downloadFolder(folder: OCFile, accountName: String)
fun cancelFolderDownload()
}
@@ -26,10 +26,7 @@ import com.nextcloud.client.account.User
import com.nextcloud.client.core.Clock
import com.nextcloud.client.di.Injectable
import com.nextcloud.client.documentscan.GeneratePdfFromImagesWork
import com.nextcloud.client.jobs.autoUpload.AutoUploadWorker
import com.nextcloud.client.jobs.download.FileDownloadWorker
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
import com.nextcloud.client.jobs.metadata.MetadataWorker
import com.nextcloud.client.jobs.offlineOperations.OfflineOperationsWorker
import com.nextcloud.client.jobs.upload.FileUploadHelper
import com.nextcloud.client.jobs.upload.FileUploadWorker
@@ -37,7 +34,6 @@ import com.nextcloud.client.preferences.AppPreferences
import com.nextcloud.utils.extensions.isWorkRunning
import com.nextcloud.utils.extensions.isWorkScheduled
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.operations.DownloadType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -94,8 +90,7 @@ internal class BackgroundJobManagerImpl(
const val JOB_PERIODIC_OFFLINE_OPERATIONS = "periodic_offline_operations"
const val JOB_PERIODIC_HEALTH_STATUS = "periodic_health_status"
const val JOB_IMMEDIATE_HEALTH_STATUS = "immediate_health_status"
const val JOB_DOWNLOAD_FOLDER = "download_folder"
const val JOB_METADATA_SYNC = "metadata_sync"
const val JOB_INTERNAL_TWO_WAY_SYNC = "internal_two_way_sync"
const val JOB_TEST = "test_job"
@@ -471,73 +466,46 @@ internal class BackgroundJobManagerImpl(
workManager.enqueueUniqueWork(
JOB_OFFLINE_OPERATIONS,
ExistingWorkPolicy.KEEP,
ExistingWorkPolicy.REPLACE,
request
)
}
override fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder) {
val syncedFolderID = syncedFolder.id
override fun schedulePeriodicFilesSyncJob(syncedFolderID: Long) {
val arguments = Data.Builder()
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
.build()
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(syncedFolder.isChargingOnly)
.putLong(FilesSyncWork.SYNCED_FOLDER_ID, syncedFolderID)
.build()
val request = periodicRequestBuilder(
jobClass = AutoUploadWorker::class,
jobClass = FilesSyncWork::class,
jobName = JOB_PERIODIC_FILES_SYNC + "_" + syncedFolderID,
intervalMins = DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES,
constraints = constraints
intervalMins = DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES
)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
DEFAULT_BACKOFF_CRITERIA_DELAY_SEC,
TimeUnit.SECONDS
)
.setInputData(arguments)
.build()
workManager.enqueueUniquePeriodicWork(
JOB_PERIODIC_FILES_SYNC + "_" + syncedFolderID,
ExistingPeriodicWorkPolicy.KEEP,
ExistingPeriodicWorkPolicy.REPLACE,
request
)
}
override fun startAutoUploadImmediately(
syncedFolder: SyncedFolder,
override fun startImmediateFilesSyncJob(
syncedFolderID: Long,
overridePowerSaving: Boolean,
contentUris: Array<String?>
changedFiles: Array<String?>
) {
val syncedFolderID = syncedFolder.id
val arguments = Data.Builder()
.putBoolean(AutoUploadWorker.OVERRIDE_POWER_SAVING, overridePowerSaving)
.putStringArray(AutoUploadWorker.CONTENT_URIS, contentUris)
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
.build()
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresCharging(syncedFolder.isChargingOnly)
.putBoolean(FilesSyncWork.OVERRIDE_POWER_SAVING, overridePowerSaving)
.putStringArray(FilesSyncWork.CHANGED_FILES, changedFiles)
.putLong(FilesSyncWork.SYNCED_FOLDER_ID, syncedFolderID)
.build()
val request = oneTimeRequestBuilder(
jobClass = AutoUploadWorker::class,
jobClass = FilesSyncWork::class,
jobName = JOB_IMMEDIATE_FILES_SYNC + "_" + syncedFolderID
)
.setInputData(arguments)
.setConstraints(constraints)
.setBackoffCriteria(
BackoffPolicy.LINEAR,
DEFAULT_BACKOFF_CRITERIA_DELAY_SEC,
TimeUnit.SECONDS
)
.build()
workManager.enqueueUniqueWork(
@@ -555,28 +523,6 @@ internal class BackgroundJobManagerImpl(
workManager.cancelAllWorkByTag(formatClassTag(FileDownloadWorker::class))
}
override fun startMetadataSyncJob(currentDirPath: String) {
val inputData = Data.Builder()
.putString(MetadataWorker.FILE_PATH, currentDirPath)
.build()
val constrains = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
val request = oneTimeRequestBuilder(MetadataWorker::class, JOB_METADATA_SYNC)
.setConstraints(constrains)
.setInputData(inputData)
.build()
workManager.enqueueUniqueWork(
JOB_METADATA_SYNC,
ExistingWorkPolicy.REPLACE,
request
)
}
override fun scheduleOfflineSync() {
val constrains = Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
@@ -637,10 +583,10 @@ internal class BackgroundJobManagerImpl(
workManager.enqueue(request)
}
private fun startFileUploadJobTag(accountName: String): String = JOB_FILES_UPLOAD + accountName
private fun startFileUploadJobTag(user: User): String = JOB_FILES_UPLOAD + user.accountName
override fun isStartFileUploadJobScheduled(accountName: String): Boolean =
workManager.isWorkScheduled(startFileUploadJobTag(accountName))
override fun isStartFileUploadJobScheduled(user: User): Boolean =
workManager.isWorkScheduled(startFileUploadJobTag(user))
/**
* This method supports initiating uploads for various scenarios, including:
@@ -654,28 +600,23 @@ internal class BackgroundJobManagerImpl(
* and cannot be determined directly from the account name or a single function
* within the worker.
*/
override fun startFilesUploadJob(user: User, uploadIds: LongArray, showSameFileAlreadyExistsNotification: Boolean) {
override fun startFilesUploadJob(user: User, uploadIds: LongArray, isAutoUpload: Boolean) {
defaultDispatcherScope.launch {
val batchSize = FileUploadHelper.MAX_FILE_COUNT
val batches = uploadIds.toList().chunked(batchSize)
val tag = startFileUploadJobTag(user.accountName)
val tag = startFileUploadJobTag(user)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val dataBuilder = Data.Builder()
.putBoolean(
FileUploadWorker.SHOW_SAME_FILE_ALREADY_EXISTS_NOTIFICATION,
showSameFileAlreadyExistsNotification
)
.putString(FileUploadWorker.ACCOUNT, user.accountName)
.putInt(FileUploadWorker.TOTAL_UPLOAD_SIZE, uploadIds.size)
val workRequests = batches.mapIndexed { index, batch ->
dataBuilder
val dataBuilder = Data.Builder()
.putBoolean(FileUploadWorker.IS_AUTO_UPLOAD, isAutoUpload)
.putString(FileUploadWorker.ACCOUNT, user.accountName)
.putLongArray(FileUploadWorker.UPLOAD_IDS, batch.toLongArray())
.putInt(FileUploadWorker.CURRENT_BATCH_INDEX, index)
.putInt(FileUploadWorker.TOTAL_UPLOAD_SIZE, uploadIds.size)
oneTimeRequestBuilder(FileUploadWorker::class, JOB_FILES_UPLOAD, user)
.addTag(tag)
@@ -704,6 +645,9 @@ internal class BackgroundJobManagerImpl(
private fun startFileDownloadJobTag(user: User, fileId: Long): String =
JOB_FOLDER_DOWNLOAD + user.accountName + fileId
override fun isStartFileDownloadJobScheduled(user: User, fileId: Long): Boolean =
workManager.isWorkScheduled(startFileDownloadJobTag(user, fileId))
override fun startFileDownloadJob(
user: User,
file: OCFile,
@@ -823,28 +767,4 @@ internal class BackgroundJobManagerImpl(
workManager.enqueueUniquePeriodicWork(JOB_INTERNAL_TWO_WAY_SYNC, ExistingPeriodicWorkPolicy.UPDATE, request)
}
override fun downloadFolder(folder: OCFile, accountName: String) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(true)
.build()
val data = Data.Builder()
.putLong(FolderDownloadWorker.FOLDER_ID, folder.fileId)
.putString(FolderDownloadWorker.ACCOUNT_NAME, accountName)
.build()
val request = oneTimeRequestBuilder(FolderDownloadWorker::class, JOB_DOWNLOAD_FOLDER)
.addTag(JOB_DOWNLOAD_FOLDER)
.setInputData(data)
.setConstraints(constraints)
.build()
workManager.enqueueUniqueWork(JOB_DOWNLOAD_FOLDER, ExistingWorkPolicy.APPEND_OR_REPLACE, request)
}
override fun cancelFolderDownload() {
workManager.cancelAllWorkByTag(JOB_DOWNLOAD_FOLDER)
}
}
@@ -1,27 +1,18 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.nextcloud.client.jobs
import android.app.Notification
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.utils.ForegroundServiceHelper
import com.owncloud.android.R
import com.owncloud.android.datamodel.ForegroundServiceType
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.FilesSyncHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* This work is triggered when OS detects change in media folders.
@@ -30,113 +21,53 @@ import kotlinx.coroutines.withContext
*
* This job must not be started on API < 24.
*/
@Suppress("TooGenericExceptionCaught")
class ContentObserverWork(
private val context: Context,
appContext: Context,
private val params: WorkerParameters,
private val syncedFolderProvider: SyncedFolderProvider,
private val powerManagementService: PowerManagementService,
private val backgroundJobManager: BackgroundJobManager
) : CoroutineWorker(context, params) {
) : Worker(appContext, params) {
companion object {
private const val TAG = "🔍" + "ContentObserverWork"
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_CONTENT_OBSERVER
private const val NOTIFICATION_ID = 774
}
override fun doWork(): Result {
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
val workerName = BackgroundJobManagerImpl.formatClassTag(this@ContentObserverWork::class)
backgroundJobManager.logStartOfWorker(workerName)
Log_OC.d(TAG, "started")
try {
if (params.triggeredContentUris.isNotEmpty()) {
Log_OC.d(TAG, "📸 content observer detected file changes.")
val notificationTitle = context.getString(R.string.content_observer_work_notification_title)
val notification = createNotification(notificationTitle)
updateForegroundInfo(notification)
checkAndTriggerAutoUpload()
// prevent worker fail because of another worker
try {
backgroundJobManager.startMediaFoldersDetectionJob()
} catch (e: Exception) {
Log_OC.d(TAG, "⚠️ media folder detection job failed :$e")
}
} else {
Log_OC.d(TAG, "⚠️ triggeredContentUris is empty — nothing to sync.")
}
rescheduleSelf()
val result = Result.success()
backgroundJobManager.logEndOfWorker(workerName, result)
Log_OC.d(TAG, "finished")
result
} catch (e: Exception) {
Log_OC.e(TAG, "❌ Exception in ContentObserverWork: ${e.message}", e)
Result.retry()
if (params.triggeredContentUris.isNotEmpty()) {
Log_OC.d(TAG, "File-sync Content Observer detected files change")
checkAndStartFileSyncJob()
backgroundJobManager.startMediaFoldersDetectionJob()
} else {
Log_OC.d(TAG, "triggeredContentUris empty")
}
recheduleSelf()
val result = Result.success()
backgroundJobManager.logEndOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class), result)
return result
}
private suspend fun updateForegroundInfo(notification: Notification) {
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
NOTIFICATION_ID,
notification,
ForegroundServiceType.DataSync
)
setForeground(foregroundInfo)
}
private fun createNotification(title: String): Notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_find_in_page)
.setOngoing(true)
.setSound(null)
.setVibrate(null)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSilent(true)
.build()
/**
* Re-schedules this observer to ensure continuous monitoring of media changes.
*/
private fun rescheduleSelf() {
Log_OC.d(TAG, "🔁 Rescheduling ContentObserverWork for continued observation.")
private fun recheduleSelf() {
backgroundJobManager.scheduleContentObserverJob()
}
private suspend fun checkAndTriggerAutoUpload() = withContext(Dispatchers.IO) {
if (powerManagementService.isPowerSavingEnabled) {
Log_OC.w(TAG, "⚡ Power saving mode active — skipping file sync.")
return@withContext
}
val enabledFoldersCount = syncedFolderProvider.countEnabledSyncedFolders()
if (enabledFoldersCount <= 0) {
Log_OC.w(TAG, "🚫 No enabled synced folders found — skipping file sync.")
return@withContext
}
val contentUris = params.triggeredContentUris.map { uri ->
// adds uri strings e.g. content://media/external/images/media/2281
uri.toString()
}.toTypedArray()
Log_OC.d(TAG, "📄 Content uris detected")
try {
FilesSyncHelper.startAutoUploadImmediatelyWithContentUris(
private fun checkAndStartFileSyncJob() {
if (!powerManagementService.isPowerSavingEnabled && syncedFolderProvider.countEnabledSyncedFolders() > 0) {
val changedFiles = mutableListOf<String>()
for (uri in params.triggeredContentUris) {
changedFiles.add(uri.toString())
}
FilesSyncHelper.startFilesSyncForAllFolders(
syncedFolderProvider,
backgroundJobManager,
false,
contentUris
changedFiles.toTypedArray()
)
Log_OC.d(TAG, "✅ auto upload triggered successfully for ${contentUris.size} file(s).")
} catch (e: Exception) {
Log_OC.e(TAG, "❌ Failed to start auto upload for changed files: ${e.message}", e)
} else {
Log_OC.w(TAG, "cant startFilesSyncForAllFolders")
}
}
companion object {
val TAG: String = ContentObserverWork::class.java.simpleName
}
}
@@ -0,0 +1,405 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Jonas Mayer <jonas.mayer@nextcloud.com>
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2017 Mario Danic <mario@lovelyhq.com>
* SPDX-FileCopyrightText: 2017 Nextcloud GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.nextcloud.client.jobs
import android.content.ContentResolver
import android.content.Context
import android.content.res.Resources
import android.text.TextUtils
import androidx.exifinterface.media.ExifInterface
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.upload.FileUploadHelper
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.client.preferences.SubFolderRule
import com.owncloud.android.R
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
import com.owncloud.android.datamodel.FilesystemDataProvider
import com.owncloud.android.datamodel.MediaFolderType
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.activity.SettingsActivity
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.FilesSyncHelper
import com.owncloud.android.utils.MimeType
import com.owncloud.android.utils.MimeTypeUtil
import java.io.File
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
@Suppress("LongParameterList") // legacy code
class FilesSyncWork(
private val context: Context,
params: WorkerParameters,
private val contentResolver: ContentResolver,
private val userAccountManager: UserAccountManager,
private val uploadsStorageManager: UploadsStorageManager,
private val connectivityService: ConnectivityService,
private val powerManagementService: PowerManagementService,
private val syncedFolderProvider: SyncedFolderProvider,
private val backgroundJobManager: BackgroundJobManager
) : Worker(context, params) {
companion object {
const val TAG = "FilesSyncJob"
const val OVERRIDE_POWER_SAVING = "overridePowerSaving"
const val CHANGED_FILES = "changedFiles"
const val SYNCED_FOLDER_ID = "syncedFolderId"
}
private lateinit var syncedFolder: SyncedFolder
@Suppress("MagicNumber", "ReturnCount")
override fun doWork(): Result {
val syncFolderId = inputData.getLong(SYNCED_FOLDER_ID, -1)
val changedFiles = inputData.getStringArray(CHANGED_FILES)
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class) + "_" + syncFolderId)
Log_OC.d(TAG, "AutoUpload started folder ID: $syncFolderId")
// Create all the providers we'll need
val resources = context.resources
val lightVersion = resources.getBoolean(R.bool.syncedFolder_light)
val filesystemDataProvider = FilesystemDataProvider(contentResolver)
val currentLocale = resources.configuration.locale
val dateFormat = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale)
dateFormat.timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
if (!setSyncedFolder(syncFolderId)) {
Log_OC.w(TAG, "AutoUpload skipped since syncedFolder ($syncFolderId) is not enabled!")
return logEndOfWorker(syncFolderId)
}
// Always first try to schedule uploads to make sure files are uploaded even if worker was killed to early
uploadFilesFromFolder(
context,
resources,
lightVersion,
filesystemDataProvider,
currentLocale,
dateFormat,
syncedFolder
)
if (canExitEarly(changedFiles, syncFolderId)) {
Log_OC.w(TAG, "AutoUpload skipped canExit conditions are met")
return logEndOfWorker(syncFolderId)
}
val user = userAccountManager.getUser(syncedFolder.account)
if (user.isPresent) {
var uploadIds = uploadsStorageManager.getCurrentUploadIds(user.get().accountName)
backgroundJobManager.startFilesUploadJob(user.get(), uploadIds, isAutoUpload = true)
}
// Get changed files from ContentObserverWork (only images and videos) or by scanning filesystem
Log_OC.d(
TAG,
"AutoUpload (${syncedFolder.remotePath}) changed files from observer: " +
changedFiles.contentToString()
)
collectChangedFiles(changedFiles)
Log_OC.d(TAG, "AutoUpload (${syncedFolder.remotePath}) finished checking files.")
uploadFilesFromFolder(
context,
resources,
lightVersion,
filesystemDataProvider,
currentLocale,
dateFormat,
syncedFolder
)
FilesSyncHelper.restartUploadsIfNeeded(
uploadsStorageManager,
userAccountManager,
connectivityService,
powerManagementService
)
return logEndOfWorker(syncFolderId)
}
private fun logEndOfWorker(syncFolderId: Long): Result {
Log_OC.d(TAG, "AutoUpload worker (${syncedFolder.remotePath}) finished")
val result = Result.success()
backgroundJobManager.logEndOfWorker(
BackgroundJobManagerImpl.formatClassTag(this::class) +
"_" + syncFolderId,
result
)
return result
}
private fun setSyncedFolder(syncedFolderID: Long): Boolean {
val syncedFolderTmp = syncedFolderProvider.getSyncedFolderByID(syncedFolderID)
if (syncedFolderTmp == null || !syncedFolderTmp.isEnabled) {
return false
}
syncedFolder = syncedFolderTmp
return true
}
@Suppress("ReturnCount")
private fun canExitEarly(changedFiles: Array<String>?, syncedFolderID: Long): Boolean {
// If we are in power save mode better to postpone scan and upload
val overridePowerSaving = inputData.getBoolean(OVERRIDE_POWER_SAVING, false)
if ((powerManagementService.isPowerSavingEnabled && !overridePowerSaving)) {
Log_OC.w(TAG, "AutoUpload skipped powerSaving is enabled!")
return true
}
if (syncedFolderID < 0) {
Log_OC.w(TAG, "AutoUpload skipped no valid syncedFolderID provided")
return true
}
// or sync worker already running
if (backgroundJobManager.bothFilesSyncJobsRunning(syncedFolderID)) {
Log_OC.w(TAG, "AutoUpload skipped another worker instance is running for $syncedFolderID")
return true
}
val calculatedScanInterval =
FilesSyncHelper.calculateScanInterval(syncedFolder, connectivityService, powerManagementService)
val totalScanInterval = (syncedFolder.lastScanTimestampMs + calculatedScanInterval)
val currentTime = System.currentTimeMillis()
val passedScanInterval = totalScanInterval <= currentTime
Log_OC.d(TAG, "AutoUpload lastScanTimestampMs: " + syncedFolder.lastScanTimestampMs)
Log_OC.d(TAG, "AutoUpload calculatedScanInterval: $calculatedScanInterval")
Log_OC.d(TAG, "AutoUpload totalScanInterval: $totalScanInterval")
Log_OC.d(TAG, "AutoUpload currentTime: $currentTime")
Log_OC.d(TAG, "AutoUpload passedScanInterval: $passedScanInterval")
if (!passedScanInterval && changedFiles.isNullOrEmpty() && !overridePowerSaving) {
Log_OC.w(
TAG,
"AutoUpload skipped since started before scan interval and nothing todo: " + syncedFolder.localPath
)
return true
}
if (syncedFolder.isChargingOnly &&
!powerManagementService.battery.isCharging &&
!powerManagementService.battery.isFull
) {
Log_OC.w(
TAG,
"AutoUpload skipped since phone is not charging: " + syncedFolder.localPath
)
return true
}
return false
}
@Suppress("MagicNumber")
private fun collectChangedFiles(changedFiles: Array<String>?) {
if (!changedFiles.isNullOrEmpty()) {
FilesSyncHelper.insertChangedEntries(syncedFolder, changedFiles)
} else {
// Check every file in synced folder for changes and update
// filesystemDataProvider database (potentially needs a long time)
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
}
syncedFolder.lastScanTimestampMs = System.currentTimeMillis()
syncedFolderProvider.updateSyncFolder(syncedFolder)
}
@Suppress("LongMethod") // legacy code
private fun uploadFilesFromFolder(
context: Context,
resources: Resources,
lightVersion: Boolean,
filesystemDataProvider: FilesystemDataProvider,
currentLocale: Locale,
sFormatter: SimpleDateFormat,
syncedFolder: SyncedFolder
) {
val uploadAction: Int?
val needsCharging: Boolean
val needsWifi: Boolean
val accountName = syncedFolder.account
val optionalUser = userAccountManager.getUser(accountName)
if (!optionalUser.isPresent) {
Log_OC.w(TAG, "AutoUpload:uploadFilesFromFolder skipped user not present")
return
}
val user = optionalUser.get()
val arbitraryDataProvider = if (lightVersion) {
ArbitraryDataProviderImpl(context)
} else {
null
}
// Ensure only new files are processed for upload.
// Files that have been previously uploaded cannot be re-uploaded,
// even if they have been deleted or moved from the target folder,
// as they are already marked as uploaded in the database.
val paths = filesystemDataProvider.getFilesForUpload(
syncedFolder.localPath,
syncedFolder.id.toString()
)
if (paths.isEmpty()) {
Log_OC.w(TAG, "AutoUpload:uploadFilesFromFolder skipped paths is empty")
return
}
val pathsAndMimes = paths.map { path ->
val file = File(path)
val localPath = file.absolutePath
val remotePath = getRemotePath(file, syncedFolder, sFormatter, lightVersion, resources, currentLocale)
val mimeType = MimeTypeUtil.getBestMimeTypeByFilename(localPath)
Log_OC.d(TAG, "AutoUpload:pathsAndMimes file.path: ${file.path}")
Log_OC.d(TAG, "AutoUpload:pathsAndMimes localPath: $localPath")
Log_OC.d(TAG, "AutoUpload:pathsAndMimes remotePath: $remotePath")
Log_OC.d(TAG, "AutoUpload:pathsAndMimes mimeType: $mimeType")
Triple(
localPath,
remotePath,
mimeType
)
}
val localPaths = pathsAndMimes.map { it.first }.toTypedArray()
val remotePaths = pathsAndMimes.map { it.second }.toTypedArray()
if (lightVersion) {
Log_OC.d(TAG, "AutoUpload:uploadFilesFromFolder light version is used")
needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging)
needsWifi = arbitraryDataProvider?.getBooleanValue(
accountName,
SettingsActivity.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI
) ?: true
val uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour)
uploadAction = getUploadAction(uploadActionString)
Log_OC.d(TAG, "AutoUpload upload action is: $uploadAction")
} else {
Log_OC.d(TAG, "AutoUpload:uploadFilesFromFolder not light version is used")
needsCharging = syncedFolder.isChargingOnly
needsWifi = syncedFolder.isWifiOnly
uploadAction = syncedFolder.uploadAction
}
FileUploadHelper.instance().uploadNewFiles(
user,
localPaths,
remotePaths,
uploadAction,
// create parent folder if not existent
true,
UploadFileOperation.CREATED_AS_INSTANT_PICTURE,
needsWifi,
needsCharging,
syncedFolder.nameCollisionPolicy,
isAutoUpload = true
)
for (path in paths) {
filesystemDataProvider.updateFilesystemFileAsSentForUpload(
path,
syncedFolder.id.toString()
)
}
}
private fun getRemotePath(
file: File,
syncedFolder: SyncedFolder,
sFormatter: SimpleDateFormat,
lightVersion: Boolean,
resources: Resources,
currentLocale: Locale
): String {
val lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter)
val remoteFolder: String
val useSubfolders: Boolean
val subFolderRule: SubFolderRule
if (lightVersion) {
Log_OC.d(TAG, "AutoUpload:getRemotePath light version is used")
useSubfolders = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders)
remoteFolder = resources.getString(R.string.syncedFolder_remote_folder)
subFolderRule = SubFolderRule.YEAR_MONTH
} else {
Log_OC.d(TAG, "AutoUpload:getRemotePath not light version is used")
useSubfolders = syncedFolder.isSubfolderByDate
remoteFolder = syncedFolder.remotePath
subFolderRule = syncedFolder.subfolderRule
}
return FileStorageUtils.getInstantUploadFilePath(
file,
currentLocale,
remoteFolder,
syncedFolder.localPath,
lastModificationTime,
useSubfolders,
subFolderRule
)
}
private fun hasExif(file: File): Boolean {
val mimeType = FileStorageUtils.getMimeTypeFromName(file.absolutePath)
return MimeType.JPEG.equals(mimeType, ignoreCase = true) || MimeType.TIFF.equals(mimeType, ignoreCase = true)
}
private fun calculateLastModificationTime(
file: File,
syncedFolder: SyncedFolder,
formatter: SimpleDateFormat
): Long {
var lastModificationTime = file.lastModified()
if (MediaFolderType.IMAGE == syncedFolder.type && hasExif(file)) {
Log_OC.d(TAG, "AutoUpload:calculateLastModificationTime exif found")
@Suppress("TooGenericExceptionCaught") // legacy code
try {
val exifInterface = ExifInterface(file.absolutePath)
val exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME)
if (!TextUtils.isEmpty(exifDate)) {
val pos = ParsePosition(0)
val dateTime = formatter.parse(exifDate, pos)
lastModificationTime = dateTime.time
Log_OC.w(TAG, "AutoUpload:calculateLastModificationTime calculatedTime is: $lastModificationTime")
} else {
Log_OC.w(TAG, "AutoUpload:calculateLastModificationTime exifDate is empty")
}
} catch (e: Exception) {
Log_OC.d(TAG, "Failed to get the proper time " + e.localizedMessage)
}
}
return lastModificationTime
}
private fun getUploadAction(action: String): Int = when (action) {
"LOCAL_BEHAVIOUR_FORGET" -> FileUploadWorker.LOCAL_BEHAVIOUR_FORGET
"LOCAL_BEHAVIOUR_MOVE" -> FileUploadWorker.LOCAL_BEHAVIOUR_MOVE
"LOCAL_BEHAVIOUR_DELETE" -> FileUploadWorker.LOCAL_BEHAVIOUR_DELETE
else -> FileUploadWorker.LOCAL_BEHAVIOUR_FORGET
}
}
@@ -78,8 +78,7 @@ class OfflineSyncWork(
true,
context,
storageManager,
true,
false
true
)
synchronizeFileOperation.execute(context)
}
@@ -1,481 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.autoUpload
import android.app.Notification
import android.app.NotificationManager
import android.content.Context
import android.content.res.Resources
import androidx.core.app.NotificationCompat
import androidx.exifinterface.media.ExifInterface
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.database.entity.UploadEntity
import com.nextcloud.client.database.entity.toOCUpload
import com.nextcloud.client.database.entity.toUploadEntity
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.client.preferences.SubFolderRule
import com.nextcloud.utils.ForegroundServiceHelper
import com.nextcloud.utils.extensions.updateStatus
import com.owncloud.android.R
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.ForegroundServiceType
import com.owncloud.android.datamodel.MediaFolderType
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.activity.SettingsActivity
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.FilesSyncHelper
import com.owncloud.android.utils.MimeType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
@Suppress("LongParameterList", "TooManyFunctions")
class AutoUploadWorker(
private val context: Context,
params: WorkerParameters,
private val userAccountManager: UserAccountManager,
private val uploadsStorageManager: UploadsStorageManager,
private val connectivityService: ConnectivityService,
private val powerManagementService: PowerManagementService,
private val syncedFolderProvider: SyncedFolderProvider,
private val backgroundJobManager: BackgroundJobManager,
private val repository: FileSystemRepository
) : CoroutineWorker(context, params) {
companion object {
const val TAG = "🔄📤" + "AutoUpload"
const val OVERRIDE_POWER_SAVING = "overridePowerSaving"
const val CONTENT_URIS = "content_uris"
const val SYNCED_FOLDER_ID = "syncedFolderId"
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD
private const val NOTIFICATION_ID = 266
}
private lateinit var syncedFolder: SyncedFolder
private val notificationManager by lazy {
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
}
@Suppress("TooGenericExceptionCaught", "ReturnCount")
override suspend fun doWork(): Result {
return try {
val syncFolderId = inputData.getLong(SYNCED_FOLDER_ID, -1)
syncedFolder = syncedFolderProvider.getSyncedFolderByID(syncFolderId)
?.takeIf { it.isEnabled } ?: return Result.failure()
// initial notification
val notification = createNotification(context.getString(R.string.upload_files))
updateForegroundInfo(notification)
/**
* Receives from [com.nextcloud.client.jobs.ContentObserverWork.checkAndTriggerAutoUpload]
*/
val contentUris = inputData.getStringArray(CONTENT_URIS)
if (canExitEarly(contentUris, syncFolderId)) {
return Result.retry()
}
collectFileChangesFromContentObserverWork(contentUris)
updateNotification()
uploadFiles(syncedFolder)
Log_OC.d(TAG, "✅ ${syncedFolder.remotePath} finished checking files.")
Result.success()
} catch (e: Exception) {
Log_OC.e(TAG, "❌ failed: ${e.message}")
Result.failure()
}
}
private fun updateNotification() {
getStartNotificationTitle()?.let { (localFolderName, remoteFolderName) ->
val startNotification = createNotification(
context.getString(
R.string.auto_upload_worker_start_text,
localFolderName,
remoteFolderName
)
)
notificationManager.notify(NOTIFICATION_ID, startNotification)
}
}
private suspend fun updateForegroundInfo(notification: Notification) {
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
NOTIFICATION_ID,
notification,
ForegroundServiceType.DataSync
)
setForeground(foregroundInfo)
}
private fun createNotification(title: String): Notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setSmallIcon(R.drawable.uploads)
.setOngoing(true)
.setSound(null)
.setVibrate(null)
.setOnlyAlertOnce(true)
.setSilent(true)
.build()
@Suppress("TooGenericExceptionCaught")
private fun getStartNotificationTitle(): Pair<String, String>? = try {
val localPath = syncedFolder.localPath
val remotePath = syncedFolder.remotePath
if (localPath.isBlank() || remotePath.isBlank()) {
null
} else {
try {
File(localPath).name to File(remotePath).name
} catch (_: Exception) {
null
}
}
} catch (_: Exception) {
null
}
@Suppress("ReturnCount")
private fun canExitEarly(contentUris: Array<String>?, syncedFolderID: Long): Boolean {
val overridePowerSaving = inputData.getBoolean(OVERRIDE_POWER_SAVING, false)
if ((powerManagementService.isPowerSavingEnabled && !overridePowerSaving)) {
Log_OC.w(TAG, "⚡ Skipping: device is in power saving mode")
return true
}
if (syncedFolderID < 0) {
Log_OC.e(TAG, "invalid sync folder id")
return true
}
if (backgroundJobManager.bothFilesSyncJobsRunning(syncedFolderID)) {
Log_OC.w(TAG, "🚧 another worker is already running for $syncedFolderID")
return true
}
val totalScanInterval = syncedFolder.getTotalScanInterval(connectivityService, powerManagementService)
val currentTime = System.currentTimeMillis()
val passedScanInterval = totalScanInterval <= currentTime
Log_OC.d(TAG, "lastScanTimestampMs: " + syncedFolder.lastScanTimestampMs)
Log_OC.d(TAG, "totalScanInterval: $totalScanInterval")
Log_OC.d(TAG, "currentTime: $currentTime")
Log_OC.d(TAG, "passedScanInterval: $passedScanInterval")
if (!passedScanInterval && contentUris.isNullOrEmpty() && !overridePowerSaving) {
Log_OC.w(
TAG,
"skipped since started before scan interval and nothing todo: " + syncedFolder.localPath
)
return true
}
return false
}
/**
* Instead of scanning the entire local folder, optional content URIs can be passed to the worker
* to detect only the relevant changes.
*/
@Suppress("MagicNumber", "TooGenericExceptionCaught")
private suspend fun collectFileChangesFromContentObserverWork(contentUris: Array<String>?) = try {
withContext(Dispatchers.IO) {
if (contentUris.isNullOrEmpty()) {
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
} else {
val isContentUrisStored = FilesSyncHelper.insertChangedEntries(syncedFolder, contentUris)
if (!isContentUrisStored) {
Log_OC.w(
TAG,
"changed content uris not stored, fallback to insert all db entries to not lose files"
)
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
}
}
syncedFolder.lastScanTimestampMs = System.currentTimeMillis()
syncedFolderProvider.updateSyncFolder(syncedFolder)
}
} catch (e: Exception) {
Log_OC.d(TAG, "Exception collectFileChangesFromContentObserverWork: $e")
}
private fun prepareDateFormat(): SimpleDateFormat {
val currentLocale = context.resources.configuration.locales[0]
return SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale).apply {
timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
}
}
private fun getUserOrReturn(syncedFolder: SyncedFolder): User? {
val optionalUser = userAccountManager.getUser(syncedFolder.account)
if (!optionalUser.isPresent) {
Log_OC.w(TAG, "user not present")
return null
}
return optionalUser.get()
}
@Suppress("DEPRECATION")
private fun getUploadSettings(syncedFolder: SyncedFolder): Triple<Boolean, Boolean, Int> {
val lightVersion = context.resources.getBoolean(R.bool.syncedFolder_light)
val accountName = syncedFolder.account
return if (lightVersion) {
Log_OC.d(TAG, "light version is used")
val arbitraryDataProvider = ArbitraryDataProviderImpl(context)
val needsCharging = context.resources.getBoolean(R.bool.syncedFolder_light_on_charging)
val needsWifi = arbitraryDataProvider.getBooleanValue(
accountName,
SettingsActivity.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI
)
val uploadActionString = context.resources.getString(R.string.syncedFolder_light_upload_behaviour)
val uploadAction = getUploadAction(uploadActionString)
Log_OC.d(TAG, "upload action is: $uploadAction")
Triple(needsCharging, needsWifi, uploadAction)
} else {
Log_OC.d(TAG, "not light version is used")
Triple(syncedFolder.isChargingOnly, syncedFolder.isWifiOnly, syncedFolder.uploadAction)
}
}
@Suppress("LongMethod", "DEPRECATION", "TooGenericExceptionCaught")
private suspend fun uploadFiles(syncedFolder: SyncedFolder) = withContext(Dispatchers.IO) {
val dateFormat = prepareDateFormat()
val user = getUserOrReturn(syncedFolder) ?: return@withContext
val ocAccount = OwnCloudAccount(user.toPlatformAccount(), context)
val client = OwnCloudClientManagerFactory.getDefaultSingleton()
.getClientFor(ocAccount, context)
val lightVersion = context.resources.getBoolean(R.bool.syncedFolder_light)
val currentLocale = context.resources.configuration.locales[0]
var lastId = 0
while (true) {
val filePathsWithIds = repository.getFilePathsWithIds(syncedFolder, lastId)
if (filePathsWithIds.isEmpty()) {
Log_OC.w(TAG, "no more files to upload at lastId: $lastId")
break
}
Log_OC.d(TAG, "Processing batch: lastId=$lastId, count=${filePathsWithIds.size}")
filePathsWithIds.forEach { (path, id) ->
val file = File(path)
val localPath = file.absolutePath
val remotePath = getRemotePath(
file,
syncedFolder,
dateFormat,
lightVersion,
context.resources,
currentLocale
)
try {
var (uploadEntity, upload) = createEntityAndUpload(user, localPath, remotePath)
try {
// Insert/update to IN_PROGRESS state before starting upload
val generatedId = uploadsStorageManager.uploadDao.insertOrReplace(uploadEntity)
uploadEntity = uploadEntity.copy(id = generatedId.toInt())
upload.uploadId = generatedId
val operation = createUploadFileOperation(upload, user)
Log_OC.d(TAG, "🕒 uploading: $localPath, id: $generatedId")
val result = operation.execute(client)
uploadsStorageManager.updateStatus(uploadEntity, result.isSuccess)
if (result.isSuccess) {
repository.markFileAsUploaded(localPath, syncedFolder)
Log_OC.d(TAG, "✅ upload completed: $localPath")
} else {
Log_OC.e(
TAG,
"❌ upload failed $localPath (${upload.accountName}): ${result.logMessage}"
)
}
} catch (e: Exception) {
uploadsStorageManager.updateStatus(
uploadEntity,
UploadsStorageManager.UploadStatus.UPLOAD_FAILED
)
Log_OC.e(
TAG,
"Exception during upload file, localPath: $localPath, remotePath: $remotePath," +
" exception: $e"
)
}
} catch (e: Exception) {
Log_OC.e(
TAG,
"Exception uploadFiles during creating entity and upload, localPath: $localPath, " +
"remotePath: $remotePath, exception: $e"
)
}
// update last id so upload can continue where it left
lastId = id
}
}
}
private fun createEntityAndUpload(user: User, localPath: String, remotePath: String): Pair<UploadEntity, OCUpload> {
val (needsCharging, needsWifi, uploadAction) = getUploadSettings(syncedFolder)
Log_OC.d(TAG, "creating oc upload for ${user.accountName}")
// Get or create upload entity
var uploadEntity = uploadsStorageManager.uploadDao.getUploadByAccountAndPaths(
localPath = localPath,
remotePath = remotePath,
accountName = user.accountName
)
val upload: OCUpload
if (uploadEntity != null) {
// Existing upload - convert and update status
upload = uploadEntity.toOCUpload(null)
upload.uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS
uploadEntity = upload.toUploadEntity()
} else {
// New upload - create with all settings
upload = OCUpload(localPath, remotePath, user.accountName).apply {
nameCollisionPolicy = syncedFolder.nameCollisionPolicy
isUseWifiOnly = needsWifi
isWhileChargingOnly = needsCharging
uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS
createdBy = UploadFileOperation.CREATED_AS_INSTANT_PICTURE
isCreateRemoteFolder = true
localAction = uploadAction
}
uploadEntity = upload.toUploadEntity()
}
return uploadEntity to upload
}
private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation = UploadFileOperation(
uploadsStorageManager,
connectivityService,
powerManagementService,
user,
null,
upload,
upload.nameCollisionPolicy,
upload.localAction,
context,
upload.isUseWifiOnly,
upload.isWhileChargingOnly,
true,
FileDataStorageManager(user, context.contentResolver)
)
private fun getRemotePath(
file: File,
syncedFolder: SyncedFolder,
sFormatter: SimpleDateFormat,
lightVersion: Boolean,
resources: Resources,
currentLocale: Locale
): String {
val lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter)
val (remoteFolder, useSubfolders, subFolderRule) = if (lightVersion) {
Triple(
resources.getString(R.string.syncedFolder_remote_folder),
resources.getBoolean(R.bool.syncedFolder_light_use_subfolders),
SubFolderRule.YEAR_MONTH
)
} else {
Triple(
syncedFolder.remotePath,
syncedFolder.isSubfolderByDate,
syncedFolder.subfolderRule
)
}
return FileStorageUtils.getInstantUploadFilePath(
file,
currentLocale,
remoteFolder,
syncedFolder.localPath,
lastModificationTime,
useSubfolders,
subFolderRule
)
}
private fun hasExif(file: File): Boolean {
val mimeType = FileStorageUtils.getMimeTypeFromName(file.absolutePath)
return MimeType.JPEG.equals(mimeType, ignoreCase = true) || MimeType.TIFF.equals(mimeType, ignoreCase = true)
}
@Suppress("NestedBlockDepth")
private fun calculateLastModificationTime(
file: File,
syncedFolder: SyncedFolder,
formatter: SimpleDateFormat
): Long {
var lastModificationTime = file.lastModified()
if (MediaFolderType.IMAGE == syncedFolder.type && hasExif(file)) {
Log_OC.d(TAG, "calculateLastModificationTime exif found")
@Suppress("TooGenericExceptionCaught")
try {
val exifInterface = ExifInterface(file.absolutePath)
val exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME)
if (!exifDate.isNullOrBlank()) {
val pos = ParsePosition(0)
val dateTime = formatter.parse(exifDate, pos)
if (dateTime != null) {
lastModificationTime = dateTime.time
Log_OC.w(TAG, "calculateLastModificationTime calculatedTime is: $lastModificationTime")
} else {
Log_OC.w(TAG, "calculateLastModificationTime dateTime is empty")
}
} else {
Log_OC.w(TAG, "calculateLastModificationTime exifDate is empty")
}
} catch (e: Exception) {
Log_OC.d(TAG, "Failed to get the proper time " + e.localizedMessage)
}
}
return lastModificationTime
}
private fun getUploadAction(action: String): Int = when (action) {
"LOCAL_BEHAVIOUR_FORGET" -> FileUploadWorker.Companion.LOCAL_BEHAVIOUR_FORGET
"LOCAL_BEHAVIOUR_MOVE" -> FileUploadWorker.Companion.LOCAL_BEHAVIOUR_MOVE
"LOCAL_BEHAVIOUR_DELETE" -> FileUploadWorker.Companion.LOCAL_BEHAVIOUR_DELETE
else -> FileUploadWorker.Companion.LOCAL_BEHAVIOUR_FORGET
}
}
@@ -1,66 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.autoUpload
import com.nextcloud.client.database.dao.FileSystemDao
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.utils.SyncedFolderUtils
import java.io.File
class FileSystemRepository(private val dao: FileSystemDao) {
companion object {
private const val TAG = "FilesystemRepository"
const val BATCH_SIZE = 50
}
@Suppress("NestedBlockDepth")
suspend fun getFilePathsWithIds(syncedFolder: SyncedFolder, lastId: Int): List<Pair<String, Int>> {
val syncedFolderId = syncedFolder.id.toString()
Log_OC.d(TAG, "Fetching candidate files for syncedFolderId = $syncedFolderId")
val entities = dao.getAutoUploadFilesEntities(syncedFolderId, BATCH_SIZE, lastId)
val filtered = mutableListOf<Pair<String, Int>>()
entities.forEach {
it.localPath?.let { path ->
val file = File(path)
if (!file.exists()) {
Log_OC.w(TAG, "Ignoring file for upload (doesn't exist): $path")
} else if (!SyncedFolderUtils.isQualifiedFolder(file.parent)) {
Log_OC.w(TAG, "Ignoring file for upload (unqualified folder): $path")
} else if (!SyncedFolderUtils.isFileNameQualifiedForAutoUpload(file.name)) {
Log_OC.w(TAG, "Ignoring file for upload (unqualified file): $path")
} else {
Log_OC.d(TAG, "Adding path to upload: $path")
if (it.id != null) {
filtered.add(path to it.id)
} else {
Log_OC.w(TAG, "cant adding path to upload, id is null")
}
}
}
}
return filtered
}
@Suppress("TooGenericExceptionCaught")
suspend fun markFileAsUploaded(localPath: String, syncedFolder: SyncedFolder) {
val syncedFolderIdStr = syncedFolder.id.toString()
try {
dao.markFileAsUploaded(localPath, syncedFolderIdStr)
Log_OC.d(TAG, "Marked file as uploaded: $localPath for syncedFolderId=$syncedFolderIdStr")
} catch (e: Exception) {
Log_OC.e(TAG, "Error marking file as uploaded: ${e.message}", e)
}
}
}
@@ -14,22 +14,13 @@ import com.nextcloud.client.jobs.notification.WorkerNotificationManager
import com.nextcloud.utils.numberFormatter.NumberFormatter
import com.owncloud.android.R
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
import java.io.File
import java.security.SecureRandom
@Suppress("TooManyFunctions")
class DownloadNotificationManager(id: Int, private val context: Context, viewThemeUtils: ViewThemeUtils) :
WorkerNotificationManager(
id,
context,
viewThemeUtils,
tickerId = R.string.downloader_download_in_progress_ticker,
channelId = NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD
) {
private var lastPercent = -1
WorkerNotificationManager(id, context, viewThemeUtils, R.string.downloader_download_in_progress_ticker) {
@Suppress("MagicNumber")
fun prepareForStart(operation: DownloadFileOperation) {
@@ -53,12 +44,6 @@ class DownloadNotificationManager(id: Int, private val context: Context, viewThe
@Suppress("MagicNumber")
fun updateDownloadProgress(percent: Int, totalToTransfer: Long) {
// If downloads are so fast, no need to notify again.
if (percent == lastPercent) {
return
}
lastPercent = percent
val progressText = NumberFormatter.getPercentageText(percent)
setProgress(percent, progressText, totalToTransfer < 0)
showNotification()
@@ -9,12 +9,10 @@ package com.nextcloud.client.jobs.download
import com.nextcloud.client.account.User
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
import com.owncloud.android.MainApp
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.DownloadType
import com.owncloud.android.utils.MimeTypeUtil
@@ -31,7 +29,6 @@ class FileDownloadHelper {
companion object {
private var instance: FileDownloadHelper? = null
private const val TAG = "FileDownloadHelper"
fun instance(): FileDownloadHelper = instance ?: synchronized(this) {
instance ?: FileDownloadHelper().also { instance = it }
@@ -47,11 +44,16 @@ class FileDownloadHelper {
return false
}
return if (file.isFolder) {
FolderDownloadWorker.isDownloading(file.fileId)
} else {
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
}
val fileStorageManager = FileDataStorageManager(user, MainApp.getAppContext().contentResolver)
val topParentId = fileStorageManager.getTopParentId(file)
val isJobScheduled = backgroundJobManager.isStartFileDownloadJobScheduled(user, file.fileId)
return isJobScheduled ||
if (file.isFolder) {
backgroundJobManager.isStartFileDownloadJobScheduled(user, topParentId)
} else {
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
}
}
fun cancelPendingOrCurrentDownloads(user: User?, files: List<OCFile>?) {
@@ -138,14 +140,4 @@ class FileDownloadHelper {
conflictUploadId
)
}
fun downloadFolder(folder: OCFile?, accountName: String) {
if (folder == null) {
Log_OC.e(TAG, "folder cannot be null, cant sync")
return
}
backgroundJobManager.downloadFolder(folder, accountName)
}
fun cancelFolderDownload() = backgroundJobManager.cancelFolderDownload()
}
@@ -38,8 +38,6 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCo
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.DownloadType
import com.owncloud.android.ui.events.EventBusFactory
import com.owncloud.android.ui.events.FileDownloadProgressEvent
import com.owncloud.android.utils.theme.ViewThemeUtils
import java.util.AbstractList
import java.util.Optional
@@ -151,8 +149,8 @@ class FileDownloadWorker(
ForegroundServiceType.DataSync
)
private fun setWorkerState(user: User?) {
WorkerStateLiveData.instance().setWorkState(WorkerState.DownloadStarted(user, currentDownload))
private fun setWorkerState(user: User?, percent: Int) {
WorkerStateLiveData.instance().setWorkState(WorkerState.DownloadStarted(user, currentDownload, percent))
}
private fun setIdleWorkerState() {
@@ -249,7 +247,7 @@ class FileDownloadWorker(
return
}
setWorkerState(user)
setWorkerState(user, 0)
Log_OC.e(TAG, "FilesDownloadWorker downloading: $downloadKey")
val isAccountExist = accountManager.exists(currentDownload?.user?.toPlatformAccount())
@@ -412,7 +410,7 @@ class FileDownloadWorker(
}
lastPercent = percent
EventBusFactory.downloadProgressEventBus.post(FileDownloadProgressEvent(percent))
setWorkerState(user, lastPercent)
}
// CHECK: Is this class still needed after conversion from Foreground Services to Worker?
@@ -1,167 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.folderDownload
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.jobs.download.FileDownloadHelper
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.DownloadType
import com.owncloud.android.ui.helpers.FileOperationsHelper
import com.owncloud.android.utils.theme.ViewThemeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
@Suppress("LongMethod")
class FolderDownloadWorker(
private val accountManager: UserAccountManager,
private val context: Context,
private val viewThemeUtils: ViewThemeUtils,
params: WorkerParameters
) : CoroutineWorker(context, params) {
companion object {
private const val TAG = "📂" + "FolderDownloadWorker"
const val FOLDER_ID = "FOLDER_ID"
const val ACCOUNT_NAME = "ACCOUNT_NAME"
private val pendingDownloads: MutableSet<Long> = ConcurrentHashMap.newKeySet<Long>()
fun isDownloading(id: Long): Boolean = pendingDownloads.contains(id)
}
private var notificationManager: FolderDownloadWorkerNotificationManager? = null
private lateinit var storageManager: FileDataStorageManager
@Suppress("TooGenericExceptionCaught", "ReturnCount", "DEPRECATION")
override suspend fun doWork(): Result {
val folderID = inputData.getLong(FOLDER_ID, -1)
if (folderID == -1L) {
return Result.failure()
}
val accountName = inputData.getString(ACCOUNT_NAME)
if (accountName == null) {
Log_OC.e(TAG, "failed accountName cannot be null")
return Result.failure()
}
val optionalUser = accountManager.getUser(accountName)
if (optionalUser.isEmpty) {
Log_OC.e(TAG, "failed user is not present")
return Result.failure()
}
val user = optionalUser.get()
storageManager = FileDataStorageManager(user, context.contentResolver)
val folder = storageManager.getFileById(folderID)
if (folder == null) {
Log_OC.e(TAG, "failed folder cannot be nul")
return Result.failure()
}
notificationManager = FolderDownloadWorkerNotificationManager(context, viewThemeUtils)
Log_OC.d(TAG, "🕒 started for ${user.accountName} downloading ${folder.fileName}")
val foregroundInfo = notificationManager?.getForegroundInfo(folder) ?: return Result.failure()
setForeground(foregroundInfo)
pendingDownloads.add(folder.fileId)
val downloadHelper = FileDownloadHelper.instance()
return withContext(Dispatchers.IO) {
try {
val files = getFiles(folder, storageManager)
val account = user.toOwnCloudAccount()
val client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(account, context)
var result = true
files.forEachIndexed { index, file ->
if (!checkDiskSize(file)) {
return@withContext Result.failure()
}
withContext(Dispatchers.Main) {
notificationManager?.showProgressNotification(
folder.fileName,
file.fileName,
index,
files.size
)
}
val operation = DownloadFileOperation(user, file, context)
val operationResult = operation.execute(client)
if (operationResult?.isSuccess == true && operation.downloadType === DownloadType.DOWNLOAD) {
getOCFile(operation)?.let { ocFile ->
downloadHelper.saveFile(ocFile, operation, storageManager)
}
}
if (!operationResult.isSuccess) {
result = false
}
}
withContext(Dispatchers.Main) {
notificationManager?.showCompletionMessage(folder.fileName, result)
}
if (result) {
Log_OC.d(TAG, "✅ completed")
Result.success()
} else {
Log_OC.d(TAG, "❌ failed")
Result.failure()
}
} catch (e: Exception) {
Log_OC.d(TAG, "❌ failed reason: $e")
Result.failure()
} finally {
pendingDownloads.remove(folder.fileId)
notificationManager?.dismiss()
}
}
}
private fun getOCFile(operation: DownloadFileOperation): OCFile? {
val file = operation.file?.fileId?.let { storageManager.getFileById(it) }
?: storageManager.getFileByDecryptedRemotePath(operation.file?.remotePath)
?: run {
Log_OC.e(TAG, "could not save ${operation.file?.remotePath}")
return null
}
return file
}
private fun getFiles(folder: OCFile, storageManager: FileDataStorageManager): List<OCFile> =
storageManager.getFolderContent(folder, false)
.filter { !it.isFolder && !it.isDown }
private suspend fun checkDiskSize(file: OCFile): Boolean {
val fileSizeInByte = file.fileLength
val availableDiskSpace = FileOperationsHelper.getAvailableSpaceOnDevice()
return if (availableDiskSpace < fileSizeInByte) {
notificationManager?.showNotAvailableDiskSpace()
false
} else {
true
}
}
}
@@ -1,113 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.folderDownload
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.work.ForegroundInfo
import com.nextcloud.client.jobs.notification.WorkerNotificationManager
import com.nextcloud.utils.ForegroundServiceHelper
import com.owncloud.android.R
import com.owncloud.android.datamodel.ForegroundServiceType
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
import kotlinx.coroutines.delay
import kotlin.random.Random
class FolderDownloadWorkerNotificationManager(private val context: Context, viewThemeUtils: ViewThemeUtils) :
WorkerNotificationManager(
id = NOTIFICATION_ID,
context,
viewThemeUtils,
tickerId = R.string.folder_download_worker_ticker_id,
channelId = NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD
) {
companion object {
private const val NOTIFICATION_ID = 391
private const val MAX_PROGRESS = 100
private const val DELAY = 1000L
}
private fun getNotification(title: String, description: String? = null, progress: Int? = null): Notification =
notificationBuilder.apply {
setSmallIcon(R.drawable.ic_sync)
setContentTitle(title)
clearActions()
description?.let {
setContentText(description)
}
progress?.let {
setProgress(MAX_PROGRESS, progress, false)
addAction(
android.R.drawable.ic_menu_close_clear_cancel,
context.getString(R.string.common_cancel),
getCancelPendingIntent()
)
}
setAutoCancel(true)
}.build()
private fun getCancelPendingIntent(): PendingIntent {
val intent = Intent(context, FolderDownloadWorkerReceiver::class.java)
return PendingIntent.getBroadcast(
context,
Random.nextInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
fun showProgressNotification(folderName: String, filename: String, currentIndex: Int, totalFileSize: Int) {
val currentFileIndex = (currentIndex + 1)
val description = context.getString(R.string.folder_download_counter, currentFileIndex, totalFileSize, filename)
val progress = (currentFileIndex * MAX_PROGRESS) / totalFileSize
val notification = getNotification(title = folderName, description = description, progress = progress)
notificationManager.notify(NOTIFICATION_ID, notification)
}
suspend fun showCompletionMessage(folderName: String, success: Boolean) {
val title = if (success) {
context.getString(R.string.folder_download_success_notification_title, folderName)
} else {
context.getString(R.string.folder_download_error_notification_title, folderName)
}
val notification = getNotification(title = title)
notificationManager.notify(NOTIFICATION_ID, notification)
delay(DELAY)
dismiss()
}
fun getForegroundInfo(folder: OCFile): ForegroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
NOTIFICATION_ID,
getNotification(folder.fileName, progress = 0),
ForegroundServiceType.DataSync
)
suspend fun showNotAvailableDiskSpace() {
val title = context.getString(R.string.folder_download_insufficient_disk_space_notification_title)
val notification = getNotification(title)
notificationManager.notify(NOTIFICATION_ID, notification)
delay(DELAY)
dismiss()
}
fun dismiss() {
notificationManager.cancel(NOTIFICATION_ID)
}
}
@@ -1,25 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2024 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.folderDownload
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.nextcloud.client.jobs.BackgroundJobManager
import com.owncloud.android.MainApp
import javax.inject.Inject
class FolderDownloadWorkerReceiver : BroadcastReceiver() {
@Inject
lateinit var backgroundJobManager: BackgroundJobManager
override fun onReceive(context: Context, intent: Intent) {
MainApp.getAppComponent().inject(this)
backgroundJobManager.cancelFolderDownload()
}
}
@@ -1,83 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.metadata
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.utils.extensions.getNonEncryptedSubfolders
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.RefreshFolderOperation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class MetadataWorker(private val context: Context, params: WorkerParameters, private val user: User) :
CoroutineWorker(context, params) {
companion object {
private const val TAG = "MetadataWorker"
const val FILE_PATH = "file_path"
}
@Suppress("DEPRECATION", "ReturnCount")
override suspend fun doWork(): Result {
val storageManager = FileDataStorageManager(user, context.contentResolver)
val filePath = inputData.getString(FILE_PATH)
if (filePath == null) {
Log_OC.e(TAG, "❌ Invalid folder path. Aborting metadata sync. $filePath")
return Result.failure()
}
val currentDir = storageManager.getFileByDecryptedRemotePath(filePath)
if (currentDir == null) {
Log_OC.e(TAG, "❌ Current directory is null. Aborting metadata sync. $filePath")
return Result.failure()
}
Log_OC.d(TAG, "🕒 Starting metadata sync for folder: $filePath")
// first check current dir
refreshFolder(currentDir, storageManager)
// then get up-to-date subfolders
val subfolders = storageManager.getNonEncryptedSubfolders(currentDir.fileId, user.accountName)
subfolders.forEach { subFolder ->
refreshFolder(subFolder, storageManager)
}
Log_OC.d(TAG, "🏁 Metadata sync completed for folder: $filePath")
return Result.success()
}
@Suppress("DEPRECATION")
private suspend fun refreshFolder(folder: OCFile, storageManager: FileDataStorageManager) =
withContext(Dispatchers.IO) {
Log_OC.d(
TAG,
"📂 eTag check\n" +
" Path: " + folder.remotePath + "\n" +
" eTag: " + folder.etag + "\n" +
" eTagOnServer: " + folder.etagOnServer
)
if (!folder.isEtagChanged) {
Log_OC.d(TAG, "Skipping ${folder.remotePath}, eTag didn't change")
return@withContext
}
Log_OC.d(TAG, "⏳ Fetching metadata for: ${folder.remotePath}")
val operation = RefreshFolderOperation(folder, storageManager, user, context)
val result = operation.execute(user, context)
if (result.isSuccess) {
Log_OC.d(TAG, "✅ Successfully fetched metadata for: ${folder.remotePath}")
} else {
Log_OC.e(TAG, "❌ Failed to fetch metadata for: ${folder.remotePath}")
}
}
}
@@ -15,31 +15,31 @@ import android.os.Handler
import android.os.Looper
import androidx.core.app.NotificationCompat
import com.owncloud.android.R
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
open class WorkerNotificationManager(
private val id: Int,
private val context: Context,
viewThemeUtils: ViewThemeUtils,
private val tickerId: Int,
channelId: String
private val tickerId: Int
) {
var currentOperationTitle: String? = null
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var notificationBuilder: NotificationCompat.Builder =
NotificationCompat.Builder(context, channelId).apply {
NotificationUtils.newNotificationBuilder(
context,
NotificationUtils.NOTIFICATION_CHANNEL_BACKGROUND_OPERATIONS,
viewThemeUtils
).apply {
setTicker(context.getString(tickerId))
setSmallIcon(R.drawable.notification_icon)
setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.notification_icon))
setStyle(NotificationCompat.BigTextStyle())
priority = NotificationCompat.PRIORITY_LOW
setSound(null)
setVibrate(null)
setOnlyAlertOnce(true)
setSilent(true)
viewThemeUtils.androidx.themeNotificationCompatBuilder(context, this)
setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_DOWNLOAD)
}
fun showNotification() {
@@ -9,18 +9,15 @@ package com.nextcloud.client.jobs.offlineOperations
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import com.nextcloud.client.database.entity.OfflineOperationEntity
import com.nextcloud.client.jobs.notification.WorkerNotificationManager
import com.nextcloud.client.jobs.offlineOperations.receiver.OfflineOperationReceiver
import com.nextcloud.utils.extensions.getErrorMessage
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.ui.activity.ConflictsResolveActivity
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
class OfflineOperationsNotificationManager(private val context: Context, viewThemeUtils: ViewThemeUtils) :
@@ -28,13 +25,12 @@ class OfflineOperationsNotificationManager(private val context: Context, viewThe
ID,
context,
viewThemeUtils,
tickerId = R.string.offline_operations_worker_notification_manager_ticker,
channelId = NotificationUtils.NOTIFICATION_CHANNEL_OFFLINE_OPERATIONS
R.string.offline_operations_worker_notification_manager_ticker
) {
companion object {
private const val ID = 121
const val ERROR_ID = 122
private const val ERROR_ID = 122
private const val ONE_HUNDRED_PERCENT = 100
}
@@ -70,18 +66,13 @@ class OfflineOperationsNotificationManager(private val context: Context, viewThe
showNotification()
}
fun showNewNotification(id: Int?, result: RemoteOperationResult<*>, operation: RemoteOperation<*>) {
fun showNewNotification(result: RemoteOperationResult<*>, operation: RemoteOperation<*>) {
val reason = (result to operation).getErrorMessage()
val text = context.getString(R.string.offline_operations_worker_notification_error_text, reason)
val cancelOfflineOperationAction = id?.let { getCancelOfflineOperationAction(it) }
notificationBuilder.run {
cancelOfflineOperationAction?.let {
addAction(it)
}
setContentTitle(text)
setOngoing(false)
setProgress(0, 0, false)
notificationManager.notify(ERROR_ID, this.build())
}
}
@@ -142,25 +133,6 @@ class OfflineOperationsNotificationManager(private val context: Context, viewThe
)
}
private fun getCancelOfflineOperationAction(id: Int): NotificationCompat.Action {
val intent = Intent(context, OfflineOperationReceiver::class.java).apply {
putExtra(OfflineOperationReceiver.ID, id)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
id,
intent,
PendingIntent.FLAG_IMMUTABLE
)
return NotificationCompat.Action(
R.drawable.ic_delete,
context.getString(R.string.common_cancel),
pendingIntent
)
}
fun dismissNotification(id: Int?) {
if (id == null) return
notificationManager.cancel(id)
@@ -34,6 +34,8 @@ import com.owncloud.android.operations.RenameFileOperation
import com.owncloud.android.utils.MimeTypeUtil
import com.owncloud.android.utils.theme.ViewThemeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
@@ -60,75 +62,173 @@ class OfflineOperationsWorker(
private val notificationManager = OfflineOperationsNotificationManager(context, viewThemeUtils)
private var repository = OfflineOperationsRepository(fileDataStorageManager)
@Suppress("TooGenericExceptionCaught")
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
try {
val jobName = inputData.getString(JOB_NAME)
Log_OC.d(TAG, "[$jobName] OfflineOperationsWorker started for user: ${user.accountName}")
val jobName = inputData.getString(JOB_NAME)
Log_OC.d(TAG, "$jobName --- OfflineOperationsWorker started ---")
// check network connection
if (!isNetworkAndServerAvailable()) {
Log_OC.w(TAG, "⚠️ No internet/server connection. Retrying later...")
return@withContext Result.retry()
}
// check offline operations
val operations = fileDataStorageManager.offlineOperationDao.getAll()
if (operations.isEmpty()) {
Log_OC.d(TAG, "Skipping, no offline operation found")
return@withContext Result.success()
}
// process offline operations
notificationManager.start()
val client = clientFactory.create(user)
processOperations(operations, client)
// finish
WorkerStateLiveData.instance().setWorkState(WorkerState.OfflineOperationsCompleted)
Log_OC.d(TAG, "🏁 Worker finished with result")
return@withContext Result.success()
} catch (e: Exception) {
Log_OC.e(TAG, "💥 ProcessOperations failed: ${e.message}")
return@withContext Result.failure()
} finally {
notificationManager.dismissNotification()
if (!isNetworkAndServerAvailable()) {
Log_OC.w(TAG, "No internet connection. Retrying later.")
return@withContext Result.retry()
}
val client = clientFactory.create(user)
notificationManager.start()
val operations = fileDataStorageManager.offlineOperationDao.getAll()
val result = processOperations(operations, client)
notificationManager.dismissNotification()
return@withContext result
}
// region Handle offline operations
@Suppress("TooGenericExceptionCaught")
private suspend fun processOperations(operations: List<OfflineOperationEntity>, client: OwnCloudClient) {
private suspend fun processOperations(operations: List<OfflineOperationEntity>, client: OwnCloudClient): Result {
val totalOperationSize = operations.size
operations.forEachIndexed { index, operation ->
try {
Log_OC.d(TAG, "Processing operation, path: ${operation.path}")
val result = executeOperation(operation, client)
handleResult(operation, totalOperationSize, index, result)
} catch (e: Exception) {
Log_OC.e(TAG, "💥 Exception while processing operation id=${operation.id}: ${e.message}")
return try {
operations.forEachIndexed { index, operation ->
try {
val result = executeOperation(operation, client)
val success = handleResult(operation, totalOperationSize, index, result)
if (!success) {
Log_OC.e(TAG, "Skipped (failed to handle result): $operation")
}
} catch (e: Exception) {
Log_OC.e(TAG, "Skipped (exception): $e")
}
}
Log_OC.i(TAG, "OfflineOperationsWorker completed successfully.")
WorkerStateLiveData.instance().setWorkState(WorkerState.OfflineOperationsCompleted)
Result.success()
} catch (e: Exception) {
Log_OC.e(TAG, "Processing failed: $e")
Result.failure()
}
}
private suspend fun isNetworkAndServerAvailable(): Boolean = suspendCoroutine { continuation ->
connectivityService.isNetworkAndServerAvailable { result ->
continuation.resume(result)
}
}
// region Operation Execution
@Suppress("ComplexCondition")
private suspend fun executeOperation(
operation: OfflineOperationEntity,
client: OwnCloudClient
): OfflineOperationResult? = withContext(Dispatchers.IO) {
val path = (operation.path)
if (path == null) {
Log_OC.w(TAG, "Offline operation skipped, file path is null: $operation")
return@withContext null
}
val remoteFile = getRemoteFile(path)
val ocFile = fileDataStorageManager.getFileByDecryptedRemotePath(operation.path)
if (remoteFile != null && ocFile != null && isFileChanged(remoteFile, ocFile)) {
Log_OC.w(TAG, "Offline operation skipped, file already exists: $operation")
if (operation.isRenameOrRemove()) {
fileDataStorageManager.offlineOperationDao.delete(operation)
notificationManager.showConflictNotificationForDeleteOrRemoveOperation(operation)
} else {
notificationManager.showConflictResolveNotification(ocFile, operation)
}
return@withContext null
}
return@withContext when (val type = operation.type) {
is OfflineOperationType.CreateFolder -> createFolder(operation, client)
is OfflineOperationType.CreateFile -> createFile(operation, client)
is OfflineOperationType.RenameFile -> renameFile(operation, client)
is OfflineOperationType.RemoveFile -> ocFile?.let { removeFile(it, client) }
else -> {
Log_OC.d(TAG, "Unsupported operation type: $type")
null
}
}
}
private fun handleResult(
@Suppress("DEPRECATION")
private suspend fun createFolder(
operation: OfflineOperationEntity,
client: OwnCloudClient
): OfflineOperationResult {
val operationType = (operation.type as OfflineOperationType.CreateFolder)
val createFolderOperation = withContext(NonCancellable) {
CreateFolderOperation(operationType.path, user, context, fileDataStorageManager)
}
return createFolderOperation.execute(client) to createFolderOperation
}
@Suppress("DEPRECATION")
private suspend fun createFile(operation: OfflineOperationEntity, client: OwnCloudClient): OfflineOperationResult {
val operationType = (operation.type as OfflineOperationType.CreateFile)
val createFileOperation = withContext(NonCancellable) {
val lastModificationDate = System.currentTimeMillis() / ONE_SECOND
UploadFileRemoteOperation(
operationType.localPath,
operationType.remotePath,
operationType.mimeType,
"",
operation.modifiedAt ?: lastModificationDate,
operation.createdAt ?: System.currentTimeMillis(),
true
)
}
return createFileOperation.execute(client) to createFileOperation
}
@Suppress("DEPRECATION")
private suspend fun renameFile(operation: OfflineOperationEntity, client: OwnCloudClient): OfflineOperationResult {
val renameFileOperation = withContext(NonCancellable) {
val operationType = (operation.type as OfflineOperationType.RenameFile)
RenameFileOperation(operation.path, operationType.newName, fileDataStorageManager)
}
return renameFileOperation.execute(client) to renameFileOperation
}
@Suppress("DEPRECATION")
private suspend fun removeFile(ocFile: OCFile, client: OwnCloudClient): OfflineOperationResult {
val removeFileOperation = withContext(NonCancellable) {
RemoveFileOperation(ocFile, false, user, true, context, fileDataStorageManager)
}
return removeFileOperation.execute(client) to removeFileOperation
}
// endregion
private suspend fun handleResult(
operation: OfflineOperationEntity,
totalOperations: Int,
currentSuccessfulOperationIndex: Int,
result: OfflineOperationResult
) {
val operationResult = result?.first ?: return
val logMessage = if (operationResult.isSuccess) "Operation completed" else "Operation failed"
): Boolean {
val operationResult = result?.first ?: return false
val logMessage = if (operationResult.isSuccess == true) "Operation completed" else "Operation failed"
Log_OC.d(TAG, "$logMessage filename: ${operation.filename}, type: ${operation.type}")
return if (result.first?.isSuccess == true) {
handleSuccessResult(operation, totalOperations, currentSuccessfulOperationIndex)
true
} else {
handleErrorResult(operation.id, result)
handleErrorResult(result)
false
}
}
private fun handleSuccessResult(
private suspend fun handleSuccessResult(
operation: OfflineOperationEntity,
totalOperations: Int,
currentSuccessfulOperationIndex: Int
@@ -143,141 +243,22 @@ class OfflineOperationsWorker(
}
fileDataStorageManager.offlineOperationDao.delete(operation)
notificationManager.update(totalOperations, currentSuccessfulOperationIndex + 1, operation.filename ?: "")
notificationManager.update(totalOperations, currentSuccessfulOperationIndex, operation.filename ?: "")
delay(ONE_SECOND)
notificationManager.dismissNotification(operation.id)
}
private fun handleErrorResult(id: Int?, result: OfflineOperationResult) {
private fun handleErrorResult(result: OfflineOperationResult) {
val operationResult = result?.first ?: return
val operation = result.second ?: return
Log_OC.e(TAG, "❌ Operation failed [id=$id]: code=${operationResult.code}, message=${operationResult.message}")
val excludedErrorCodes =
listOf(RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS, RemoteOperationResult.ResultCode.LOCKED)
val excludedErrorCodes = listOf(RemoteOperationResult.ResultCode.FOLDER_ALREADY_EXISTS)
if (!excludedErrorCodes.contains(operationResult.code)) {
notificationManager.showNewNotification(id, operationResult, operation)
} else {
Log_OC.d(TAG, "ℹ️ Ignored error: ${operationResult.code}")
notificationManager.showNewNotification(operationResult, operation)
}
}
// endregion
private suspend fun isNetworkAndServerAvailable(): Boolean = suspendCoroutine { continuation ->
connectivityService.isNetworkAndServerAvailable { result ->
continuation.resume(result)
}
}
// region Operation Execution
@Suppress("ComplexCondition", "LongMethod")
private suspend fun executeOperation(
operation: OfflineOperationEntity,
client: OwnCloudClient
): OfflineOperationResult? = withContext(Dispatchers.IO) {
var path = (operation.path)
if (path == null) {
Log_OC.w(TAG, "⚠️ Skipped: path is null for operation id=${operation.id}")
return@withContext null
}
if (operation.type is OfflineOperationType.CreateFile && path.endsWith(OCFile.PATH_SEPARATOR)) {
Log_OC.w(
TAG,
"Create file operation should not ends with path separator removing suffix, " +
"operation id=${operation.id}"
)
path = path.removeSuffix(OCFile.PATH_SEPARATOR)
}
val remoteFile = getRemoteFile(path)
val ocFile = fileDataStorageManager.getFileByDecryptedRemotePath(path)
if (remoteFile != null && ocFile != null && isFileChanged(remoteFile, ocFile)) {
Log_OC.w(TAG, "⚠️ Conflict detected: File already exists on server. Skipping operation id=${operation.id}")
if (operation.isRenameOrRemove()) {
Log_OC.d(TAG, "🗑 Removing conflicting rename/remove operation id=${operation.id}")
fileDataStorageManager.offlineOperationDao.delete(operation)
notificationManager.showConflictNotificationForDeleteOrRemoveOperation(operation)
} else {
Log_OC.d(TAG, "📌 Showing conflict resolution for operation id=${operation.id}")
notificationManager.showConflictResolveNotification(ocFile, operation)
}
return@withContext null
}
if (operation.isRenameOrRemove() && ocFile == null) {
Log_OC.d(TAG, "Skipping, attempting to delete or rename non-existing file")
fileDataStorageManager.offlineOperationDao.delete(operation)
return@withContext null
}
if (operation.isCreate() && remoteFile != null && ocFile != null && !isFileChanged(remoteFile, ocFile)) {
Log_OC.d(TAG, "Skipping, attempting to create same file creation")
fileDataStorageManager.offlineOperationDao.delete(operation)
return@withContext null
}
return@withContext when (val type = operation.type) {
is OfflineOperationType.CreateFolder -> {
Log_OC.d(TAG, "📂 Creating folder at ${type.path}")
createFolder(operation, client)
}
is OfflineOperationType.CreateFile -> {
Log_OC.d(TAG, "📤 Uploading file: local=${type.localPath} → remote=${type.remotePath}")
createFile(operation, client)
}
is OfflineOperationType.RenameFile -> {
Log_OC.d(TAG, "✏️ Renaming ${operation.path} → ${type.newName}")
renameFile(operation, client)
}
is OfflineOperationType.RemoveFile -> {
Log_OC.d(TAG, "🗑 Removing file: ${operation.path}")
ocFile?.let { removeFile(it, client) }
}
else -> {
Log_OC.d(TAG, "⚠️ Unsupported operation type: $type")
null
}
}
}
@Suppress("DEPRECATION")
private fun createFolder(operation: OfflineOperationEntity, client: OwnCloudClient): OfflineOperationResult {
val operationType = (operation.type as OfflineOperationType.CreateFolder)
val createFolderOperation = CreateFolderOperation(operationType.path, user, context, fileDataStorageManager)
return createFolderOperation.execute(client) to createFolderOperation
}
@Suppress("DEPRECATION")
private fun createFile(operation: OfflineOperationEntity, client: OwnCloudClient): OfflineOperationResult {
val operationType = (operation.type as OfflineOperationType.CreateFile)
val lastModificationDate = System.currentTimeMillis() / ONE_SECOND
val createFileOperation = UploadFileRemoteOperation(
operationType.localPath,
operationType.remotePath,
operationType.mimeType,
"",
operation.modifiedAt ?: lastModificationDate,
operation.createdAt ?: System.currentTimeMillis(),
true
)
return createFileOperation.execute(client) to createFileOperation
}
@Suppress("DEPRECATION")
private fun renameFile(operation: OfflineOperationEntity, client: OwnCloudClient): OfflineOperationResult {
val operationType = (operation.type as OfflineOperationType.RenameFile)
val renameFileOperation = RenameFileOperation(operation.path, operationType.newName, fileDataStorageManager)
return renameFileOperation.execute(client) to renameFileOperation
}
@Suppress("DEPRECATION")
private fun removeFile(ocFile: OCFile, client: OwnCloudClient): OfflineOperationResult {
val removeFileOperation = RemoveFileOperation(ocFile, false, user, true, context, fileDataStorageManager)
return removeFileOperation.execute(client) to removeFileOperation
}
// endregion
@Suppress("DEPRECATION")
private fun getRemoteFile(remotePath: String): RemoteFile? {
@@ -1,41 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.client.jobs.offlineOperations.receiver
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.nextcloud.client.jobs.offlineOperations.OfflineOperationsNotificationManager
import com.owncloud.android.MainApp
import com.owncloud.android.datamodel.FileDataStorageManager
import javax.inject.Inject
class OfflineOperationReceiver : BroadcastReceiver() {
companion object {
const val ID = "id"
}
@Inject
lateinit var storageManager: FileDataStorageManager
override fun onReceive(context: Context, intent: Intent) {
MainApp.getAppComponent().inject(this)
val id = intent.getIntExtra(ID, -1)
if (id == -1) {
return
}
storageManager.offlineOperationDao.deleteById(id)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(
OfflineOperationsNotificationManager.ERROR_ID
)
}
}
@@ -7,14 +7,11 @@
*/
package com.nextcloud.client.jobs.upload
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.database.entity.toOCUpload
import com.nextcloud.client.database.entity.toUploadEntity
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.BackgroundJobManager
@@ -23,7 +20,6 @@ import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.utils.extensions.getUploadIds
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
@@ -39,12 +35,13 @@ import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.FileUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Semaphore
import javax.inject.Inject
@@ -186,7 +183,7 @@ class FileUploadHelper {
accountNames.forEach { accountName ->
val user = accountManager.getUser(accountName)
if (user.isPresent) {
backgroundJobManager.startFilesUploadJob(user.get(), failedUploads.getUploadIds(), false)
backgroundJobManager.startFilesUploadJob(user.get(), failedUploads.getUploadIds())
}
}
@@ -205,10 +202,10 @@ class FileUploadHelper {
requiresWifi: Boolean,
requiresCharging: Boolean,
nameCollisionPolicy: NameCollisionPolicy,
showSameFileAlreadyExistsNotification: Boolean = true
isAutoUpload: Boolean = false
) {
val uploads = localPaths.mapIndexed { index, localPath ->
val result = OCUpload(localPath, remotePaths[index], user.accountName).apply {
OCUpload(localPath, remotePaths[index], user.accountName).apply {
this.nameCollisionPolicy = nameCollisionPolicy
isUseWifiOnly = requiresWifi
isWhileChargingOnly = requiresCharging
@@ -217,51 +214,78 @@ class FileUploadHelper {
isCreateRemoteFolder = createRemoteFolder
localAction = localBehavior
}
val id = uploadsStorageManager.uploadDao.insertOrReplace(result.toUploadEntity())
result.uploadId = id
result
}
backgroundJobManager.startFilesUploadJob(user, uploads.getUploadIds(), showSameFileAlreadyExistsNotification)
uploadsStorageManager.storeUploads(uploads)
backgroundJobManager.startFilesUploadJob(user, uploads.getUploadIds(), isAutoUpload)
}
fun removeFileUpload(remotePath: String, accountName: String) {
uploadsStorageManager.uploadDao.deleteByAccountAndRemotePath(accountName, remotePath)
}
try {
val user = accountManager.getUser(accountName).get()
fun updateUploadStatus(remotePath: String, accountName: String, status: UploadStatus) {
ioScope.launch {
uploadsStorageManager.uploadDao.updateStatus(remotePath, accountName, status.value)
// need to update now table in mUploadsStorageManager,
// since the operation will not get to be run by FileUploader#uploadFile
uploadsStorageManager.removeUpload(accountName, remotePath)
val uploadIds = uploadsStorageManager.getCurrentUploadIds(user.accountName)
cancelAndRestartUploadJob(user, uploadIds)
} catch (e: NoSuchElementException) {
Log_OC.e(TAG, "Error cancelling current upload because user does not exist!: " + e.message)
}
}
fun getUploadsByStatus(accountName: String, status: UploadStatus, onCompleted: (Array<OCUpload>) -> Unit) {
fun cancelFileUpload(remotePath: String, accountName: String) {
ioScope.launch {
val result =
uploadsStorageManager.uploadDao.getUploadsByStatus(accountName, status.value)
.map { it.toOCUpload(null) }.toTypedArray()
onCompleted(result)
val upload = uploadsStorageManager.getUploadByRemotePath(remotePath)
if (upload != null) {
cancelFileUploads(listOf(upload), accountName)
} else {
Log_OC.e(TAG, "Error cancelling current upload because upload does not exist!")
}
}
}
fun cancelFileUploads(uploads: List<OCUpload>, accountName: String) {
for (upload in uploads) {
upload.uploadStatus = UploadStatus.UPLOAD_CANCELLED
uploadsStorageManager.updateUpload(upload)
}
try {
val user = accountManager.getUser(accountName).get()
cancelAndRestartUploadJob(user, uploads.getUploadIds())
} catch (e: NoSuchElementException) {
Log_OC.e(TAG, "Error restarting upload job because user does not exist!: " + e.message)
}
}
fun cancelAndRestartUploadJob(user: User, uploadIds: LongArray) {
backgroundJobManager.run {
cancelFilesUploadJob(user)
startFilesUploadJob(user, uploadIds, false)
startFilesUploadJob(user, uploadIds)
}
}
@Suppress("ReturnCount")
fun isUploading(remotePath: String?, accountName: String?): Boolean {
accountName ?: return false
if (!backgroundJobManager.isStartFileUploadJobScheduled(accountName)) {
fun isUploading(user: User?, file: OCFile?): Boolean {
if (user == null || file == null || !backgroundJobManager.isStartFileUploadJobScheduled(user)) {
return false
}
remotePath ?: return false
val upload = uploadsStorageManager.uploadDao.getByRemotePath(remotePath)
return upload?.status == UploadStatus.UPLOAD_IN_PROGRESS.value ||
FileUploadWorker.isUploading(remotePath, accountName)
val uploadCompletableFuture = CompletableFuture.supplyAsync {
uploadsStorageManager.getUploadByRemotePath(file.remotePath)
}
return try {
val upload = uploadCompletableFuture.get()
if (upload != null) {
upload.uploadStatus == UploadStatus.UPLOAD_IN_PROGRESS
} else {
false
}
} catch (e: ExecutionException) {
false
} catch (e: InterruptedException) {
false
}
}
private fun checkConnectivity(connectivityService: ConnectivityService): Boolean {
@@ -340,7 +364,7 @@ class FileUploadHelper {
val uploads = existingFiles.map { file ->
file?.let {
val result = OCUpload(file, user).apply {
OCUpload(file, user).apply {
fileSize = file.fileLength
this.nameCollisionPolicy = nameCollisionPolicy
isCreateRemoteFolder = true
@@ -349,14 +373,11 @@ class FileUploadHelper {
isWhileChargingOnly = false
uploadStatus = UploadStatus.UPLOAD_IN_PROGRESS
}
val id = uploadsStorageManager.uploadDao.insertOrReplace(result.toUploadEntity())
result.uploadId = id
result
}
}
uploadsStorageManager.storeUploads(uploads)
val uploadIds: LongArray = uploads.filterNotNull().map { it.uploadId }.toLongArray()
backgroundJobManager.startFilesUploadJob(user, uploadIds, true)
backgroundJobManager.startFilesUploadJob(user, uploadIds)
}
/**
@@ -400,7 +421,7 @@ class FileUploadHelper {
upload.uploadStatus = UploadStatus.UPLOAD_IN_PROGRESS
uploadsStorageManager.updateUpload(upload)
backgroundJobManager.startFilesUploadJob(user, longArrayOf(upload.uploadId), false)
backgroundJobManager.startFilesUploadJob(user, longArrayOf(upload.uploadId))
}
fun cancel(accountName: String) {
@@ -438,14 +459,6 @@ class FileUploadHelper {
return false
}
fun showFileUploadLimitMessage(activity: Activity) {
val message = activity.getString(
R.string.file_upload_limit_message,
MAX_FILE_COUNT
)
DisplayUtils.showSnackMessage(activity, message)
}
class UploadNotificationActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val accountName = intent.getStringExtra(FileUploadWorker.EXTRA_ACCOUNT_NAME)
@@ -461,9 +474,7 @@ class FileUploadHelper {
return
}
FileUploadWorker.cancelCurrentUpload(remotePath, accountName, onCompleted = {
instance().updateUploadStatus(remotePath, accountName, UploadStatus.UPLOAD_CANCELLED)
})
instance().cancelFileUpload(remotePath, accountName)
}
}
}
@@ -7,12 +7,10 @@
*/
package com.nextcloud.client.jobs.upload
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.CoroutineWorker
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
@@ -23,29 +21,20 @@ import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.client.preferences.AppPreferences
import com.nextcloud.model.WorkerState
import com.nextcloud.model.WorkerStateLiveData
import com.nextcloud.utils.ForegroundServiceHelper
import com.nextcloud.utils.extensions.getPercent
import com.nextcloud.utils.extensions.updateStatus
import com.owncloud.android.R
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.ForegroundServiceType
import com.owncloud.android.datamodel.ThumbnailsCacheManager
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.db.OCUpload
import com.owncloud.android.lib.common.OwnCloudAccount
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory
import com.owncloud.android.lib.common.network.OnDatatransferProgressListener
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.ErrorMessageAdapter
import com.owncloud.android.utils.theme.ViewThemeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.random.Random
@@ -61,7 +50,7 @@ class FileUploadWorker(
val preferences: AppPreferences,
val context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params),
) : Worker(context, params),
OnDatatransferProgressListener {
companion object {
@@ -73,7 +62,7 @@ class FileUploadWorker(
const val UPLOAD_IDS = "uploads_ids"
const val CURRENT_BATCH_INDEX = "batch_index"
const val TOTAL_UPLOAD_SIZE = "total_upload_size"
const val SHOW_SAME_FILE_ALREADY_EXISTS_NOTIFICATION = "show_same_file_already_exists_notification"
const val IS_AUTO_UPLOAD = "is_auto_upload"
var currentUploadFileOperation: UploadFileOperation? = null
@@ -101,44 +90,19 @@ class FileUploadWorker(
fun getUploadStartMessage(): String = FileUploadWorker::class.java.name + UPLOAD_START_MESSAGE
fun getUploadFinishMessage(): String = FileUploadWorker::class.java.name + UPLOAD_FINISH_MESSAGE
fun cancelCurrentUpload(remotePath: String, accountName: String, onCompleted: () -> Unit) {
currentUploadFileOperation?.let {
if (it.remotePath == remotePath && it.user.accountName == accountName) {
it.cancel(ResultCode.USER_CANCELLED)
onCompleted()
}
}
}
fun isUploading(remotePath: String?, accountName: String?): Boolean {
currentUploadFileOperation?.let {
return it.remotePath == remotePath && it.user.accountName == accountName
}
return false
}
}
private var lastPercent = 0
private val notificationId = Random.nextInt()
private val notificationManager = UploadNotificationManager(context, viewThemeUtils, notificationId)
private val notificationManager = UploadNotificationManager(context, viewThemeUtils, Random.nextInt())
private val intents = FileUploaderIntents(context)
private val fileUploaderDelegate = FileUploaderDelegate()
@Suppress("TooGenericExceptionCaught")
override suspend fun doWork(): Result = try {
override fun doWork(): Result = try {
Log_OC.d(TAG, "FileUploadWorker started")
val workerName = BackgroundJobManagerImpl.formatClassTag(this::class)
backgroundJobManager.logStartOfWorker(workerName)
val notificationTitle = notificationManager.currentOperationTitle
?: context.getString(R.string.foreground_service_upload)
val notification = createNotification(notificationTitle)
updateForegroundInfo(notification)
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
val result = uploadFiles()
backgroundJobManager.logEndOfWorker(workerName, result)
backgroundJobManager.logEndOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class), result)
notificationManager.dismissNotification()
if (result == Result.success()) {
setIdleWorkerState()
@@ -146,37 +110,17 @@ class FileUploadWorker(
result
} catch (t: Throwable) {
Log_OC.e(TAG, "Error caught at FileUploadWorker $t")
cleanup()
Result.failure()
}
private suspend fun updateForegroundInfo(notification: Notification) {
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
notificationId,
notification,
ForegroundServiceType.DataSync
)
setForeground(foregroundInfo)
}
private fun createNotification(title: String): Notification =
NotificationCompat.Builder(context, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD)
.setContentTitle(title)
.setSmallIcon(R.drawable.uploads)
.setOngoing(true)
.setSound(null)
.setVibrate(null)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSilent(true)
.build()
private fun cleanup() {
override fun onStopped() {
Log_OC.e(TAG, "FileUploadWorker stopped")
setIdleWorkerState()
currentUploadFileOperation?.cancel(null)
notificationManager.dismissNotification()
super.onStopped()
}
private fun setWorkerState(user: User?) {
@@ -188,62 +132,62 @@ class FileUploadWorker(
}
@Suppress("ReturnCount", "LongMethod")
private suspend fun uploadFiles(): Result = withContext(Dispatchers.IO) {
private fun uploadFiles(): Result {
val accountName = inputData.getString(ACCOUNT)
if (accountName == null) {
Log_OC.e(TAG, "accountName is null")
return@withContext Result.failure()
return Result.failure()
}
val uploadIds = inputData.getLongArray(UPLOAD_IDS)
if (uploadIds == null) {
Log_OC.e(TAG, "uploadIds is null")
return@withContext Result.failure()
return Result.failure()
}
val currentBatchIndex = inputData.getInt(CURRENT_BATCH_INDEX, -1)
if (currentBatchIndex == -1) {
Log_OC.e(TAG, "currentBatchIndex is -1, cancelling")
return@withContext Result.failure()
return Result.failure()
}
val totalUploadSize = inputData.getInt(TOTAL_UPLOAD_SIZE, -1)
if (totalUploadSize == -1) {
Log_OC.e(TAG, "totalUploadSize is -1, cancelling")
return@withContext Result.failure()
return Result.failure()
}
// since worker's policy is append or replace and account name comes from there no need check in the loop
val optionalUser = userAccountManager.getUser(accountName)
if (!optionalUser.isPresent) {
Log_OC.e(TAG, "User not found for account: $accountName")
return@withContext Result.failure()
}
val user = optionalUser.get()
val previouslyUploadedFileSize = currentBatchIndex * FileUploadHelper.MAX_FILE_COUNT
val uploads = uploadsStorageManager.getUploadsByIds(uploadIds, accountName)
val ocAccount = OwnCloudAccount(user.toPlatformAccount(), context)
val client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context)
val uploads = uploadIds.map { id -> uploadsStorageManager.getUploadById(id) }.filterNotNull()
for ((index, upload) in uploads.withIndex()) {
ensureActive()
if (preferences.isGlobalUploadPaused) {
Log_OC.d(TAG, "Upload is paused, skip uploading files!")
notificationManager.notifyPaused(
intents.notificationStartIntent(null)
)
return@withContext Result.success()
return Result.success()
}
if (canExitEarly()) {
notificationManager.showConnectionErrorNotification()
return@withContext Result.failure()
return Result.failure()
}
setWorkerState(user)
val operation = createUploadFileOperation(upload, user)
val user = userAccountManager.getUser(accountName)
if (!user.isPresent) {
uploadsStorageManager.removeUpload(upload.uploadId)
continue
}
if (isStopped) {
continue
}
setWorkerState(user.get())
val operation = createUploadFileOperation(upload, user.get())
currentUploadFileOperation = operation
val currentIndex = (index + 1)
@@ -256,16 +200,12 @@ class FileUploadWorker(
totalUploadSize = totalUploadSize
)
val result = withContext(Dispatchers.IO) {
upload(operation, user, client)
}
val entity = uploadsStorageManager.uploadDao.getUploadById(upload.uploadId, accountName)
uploadsStorageManager.updateStatus(entity, result.isSuccess)
val result = upload(operation, user.get())
currentUploadFileOperation = null
sendUploadFinishEvent(totalUploadSize, currentUploadIndex, operation, result)
}
return@withContext Result.success()
return Result.success()
}
private fun sendUploadFinishEvent(
@@ -322,16 +262,15 @@ class FileUploadWorker(
}
@Suppress("TooGenericExceptionCaught", "DEPRECATION")
private fun upload(
uploadFileOperation: UploadFileOperation,
user: User,
client: OwnCloudClient
): RemoteOperationResult<Any?> {
private fun upload(uploadFileOperation: UploadFileOperation, user: User): RemoteOperationResult<Any?> {
lateinit var result: RemoteOperationResult<Any?>
try {
val storageManager = uploadFileOperation.storageManager
result = uploadFileOperation.execute(client)
val ocAccount = OwnCloudAccount(user.toPlatformAccount(), context)
val uploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context)
result = uploadFileOperation.execute(uploadClient)
val task = ThumbnailsCacheManager.ThumbnailGenerationTask(storageManager, user)
val file = File(uploadFileOperation.originalStoragePath)
val remoteId: String? = uploadFileOperation.file.remoteId
@@ -359,8 +298,7 @@ class FileUploadWorker(
uploadResult: RemoteOperationResult<Any?>
) {
Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.code)
val showSameFileAlreadyExistsNotification =
inputData.getBoolean(SHOW_SAME_FILE_ALREADY_EXISTS_NOTIFICATION, false)
val isAutoUpload = inputData.getBoolean(IS_AUTO_UPLOAD, false)
if (uploadResult.isSuccess) {
notificationManager.dismissOldErrorNotification(uploadFileOperation)
@@ -380,7 +318,7 @@ class FileUploadWorker(
context
)
) {
if (showSameFileAlreadyExistsNotification) {
if (!isAutoUpload) {
notificationManager.showSameFileAlreadyExistsNotification(uploadFileOperation.fileName)
}
@@ -403,10 +341,6 @@ class FileUploadWorker(
return
}
if (uploadResult.code == ResultCode.USER_CANCELLED) {
return
}
notificationManager.run {
val errorMessage = ErrorMessageAdapter.getErrorCauseMessage(
uploadResult,
@@ -19,13 +19,7 @@ import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
class UploadNotificationManager(private val context: Context, viewThemeUtils: ViewThemeUtils, id: Int) :
WorkerNotificationManager(
id,
context,
viewThemeUtils,
tickerId = R.string.foreground_service_upload,
channelId = NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD
) {
WorkerNotificationManager(id, context, viewThemeUtils, R.string.foreground_service_upload) {
@Suppress("MagicNumber")
fun prepareForStart(
@@ -132,7 +132,6 @@ class WhatsNewActivity :
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onFinish()
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
@@ -63,12 +63,6 @@ public interface AppPreferences {
boolean isShowHiddenFilesEnabled();
void setShowHiddenFilesEnabled(boolean enabled);
boolean isSortFoldersBeforeFiles();
void setSortFoldersBeforeFiles(boolean enabled);
boolean isSortFavoritesFirst();
void setSortFavoritesFirst(boolean enabled);
boolean isShowEcosystemApps();
void setShowEcosystemApps(boolean enabled);
@@ -350,6 +344,10 @@ public interface AppPreferences {
long getPhotoSearchTimestamp();
boolean isPowerCheckDisabled();
void setPowerCheckDisabled(boolean value);
void increasePinWrongAttempts();
void resetPinWrongAttempts();
@@ -397,7 +395,4 @@ public interface AppPreferences {
int getPassCodeDelay();
void setPassCodeDelay(int value);
String getLastDisplayedAccountName();
void setLastDisplayedAccountName(String lastDisplayedAccountName);
}
@@ -70,8 +70,6 @@ public final class AppPreferencesImpl implements AppPreferences {
private static final String PREF__INSTANT_UPLOADING = "instant_uploading";
private static final String PREF__INSTANT_VIDEO_UPLOADING = "instant_video_uploading";
private static final String PREF__SHOW_HIDDEN_FILES = "show_hidden_files_pref";
private static final String PREF__SORT_FOLDERS_BEFORE_FILES = "sort_folders_before_files";
private static final String PREF__SORT_FAVORITES_FIRST = "sort_favorites_first";
private static final String PREF__SHOW_ECOSYSTEM_APPS = "show_ecosystem_apps";
private static final String PREF__LEGACY_CLEAN = "legacyClean";
private static final String PREF__KEYS_MIGRATION = "keysMigration";
@@ -90,6 +88,7 @@ public final class AppPreferencesImpl implements AppPreferences {
private static final String PREF__SELECTED_ACCOUNT_NAME = "select_oc_account";
private static final String PREF__MIGRATED_USER_ID = "migrated_user_id";
private static final String PREF__PHOTO_SEARCH_TIMESTAMP = "photo_search_timestamp";
private static final String PREF__POWER_CHECK_DISABLED = "power_check_disabled";
private static final String PREF__PIN_BRUTE_FORCE_COUNT = "pin_brute_force_count";
private static final String PREF__UID_PID = "uid_pid";
@@ -111,8 +110,6 @@ public final class AppPreferencesImpl implements AppPreferences {
private static final String PREF__PASSCODE_DELAY_IN_SECONDS = "passcode_delay_in_seconds";
private static final String PREF_LAST_DISPLAYED_ACCOUNT_NAME = "last_displayed_user";
private static final String LOG_ENTRY = "log_entry";
private final Context context;
@@ -230,26 +227,6 @@ public final class AppPreferencesImpl implements AppPreferences {
preferences.edit().putBoolean(PREF__SHOW_HIDDEN_FILES, enabled).apply();
}
@Override
public boolean isSortFoldersBeforeFiles() {
return preferences.getBoolean(PREF__SORT_FOLDERS_BEFORE_FILES, true);
}
@Override
public void setSortFoldersBeforeFiles(boolean enabled) {
preferences.edit().putBoolean(PREF__SORT_FOLDERS_BEFORE_FILES, enabled).apply();
}
@Override
public boolean isSortFavoritesFirst() {
return preferences.getBoolean(PREF__SORT_FAVORITES_FIRST, true);
}
@Override
public void setSortFavoritesFirst(boolean enabled) {
preferences.edit().putBoolean(PREF__SORT_FAVORITES_FIRST, enabled).apply();
}
@Override
public boolean isShowEcosystemApps() {
return preferences.getBoolean(PREF__SHOW_ECOSYSTEM_APPS, true);
@@ -710,6 +687,16 @@ public final class AppPreferencesImpl implements AppPreferences {
return preferenceName + "_" + folderIdString;
}
@Override
public boolean isPowerCheckDisabled() {
return preferences.getBoolean(PREF__POWER_CHECK_DISABLED, false);
}
@Override
public void setPowerCheckDisabled(boolean value) {
preferences.edit().putBoolean(PREF__POWER_CHECK_DISABLED, value).apply();
}
public void increasePinWrongAttempts() {
int count = preferences.getInt(PREF__PIN_BRUTE_FORCE_COUNT, 0);
preferences.edit().putInt(PREF__PIN_BRUTE_FORCE_COUNT, count + 1).apply();
@@ -845,14 +832,4 @@ public final class AppPreferencesImpl implements AppPreferences {
public void setPassCodeDelay(int value) {
preferences.edit().putInt(PREF__PASSCODE_DELAY_IN_SECONDS, value).apply();
}
@Override
public String getLastDisplayedAccountName() {
return preferences.getString(PREF_LAST_DISPLAYED_ACCOUNT_NAME, null);
}
@Override
public void setLastDisplayedAccountName(String lastDisplayedAccountName) {
preferences.edit().putString(PREF_LAST_DISPLAYED_ACCOUNT_NAME, lastDisplayedAccountName).apply();
}
}
@@ -18,11 +18,11 @@ enum class SearchResultEntryType {
Unknown;
fun iconId(): Int = when (this) {
CalendarEvent -> R.drawable.file_calendar
Folder -> R.drawable.folder
Note -> R.drawable.ic_edit
Contact -> R.drawable.file_vcard
CalendarEvent -> R.drawable.file_calendar
Deck -> R.drawable.ic_deck
Unknown -> R.drawable.ic_find_in_page
else -> R.drawable.ic_find_in_page
}
}
@@ -1,38 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.model
import android.view.Menu
import com.owncloud.android.R
enum class ToolbarItem(val navId: Int, val titleId: Int, val style: ToolbarStyle) {
NONE(Menu.NONE, R.string.drawer_item_all_files, ToolbarStyle.SEARCH),
ALL_FILES(R.id.nav_all_files, R.string.drawer_item_all_files, ToolbarStyle.SEARCH),
PERSONAL_FILES(R.id.nav_personal_files, R.string.drawer_item_personal_files, ToolbarStyle.SEARCH),
ACTIVITIES(R.id.nav_activity, R.string.drawer_item_activities, ToolbarStyle.PLAIN),
FAVORITES(R.id.nav_favorites, R.string.drawer_item_favorites, ToolbarStyle.PLAIN),
GALLERY(R.id.nav_gallery, R.string.drawer_item_gallery, ToolbarStyle.PLAIN),
SHARED(R.id.nav_shared, R.string.drawer_item_shared, ToolbarStyle.PLAIN),
GROUP_FOLDERS(R.id.nav_groupfolders, R.string.drawer_item_groupfolders, ToolbarStyle.PLAIN),
ON_DEVICE(R.id.nav_on_device, R.string.drawer_item_on_device, ToolbarStyle.PLAIN),
RECENTLY_MODIFIED(R.id.nav_recently_modified, R.string.drawer_item_recently_modified, ToolbarStyle.PLAIN),
ASSISTANT(R.id.nav_assistant, R.string.drawer_item_assistant, ToolbarStyle.PLAIN),
UPLOADS(R.id.nav_uploads, R.string.drawer_item_uploads_list, ToolbarStyle.PLAIN),
SETTINGS(R.id.nav_settings, R.string.actionbar_settings, ToolbarStyle.PLAIN),
COMMUNITY(R.id.nav_community, R.string.drawer_community, ToolbarStyle.PLAIN),
TRASHBIN(R.id.nav_trashbin, R.string.drawer_item_trashbin, ToolbarStyle.PLAIN);
companion object {
fun fromNavId(navId: Int): ToolbarItem? = entries.find { it.navId == navId }
}
}
enum class ToolbarStyle {
PLAIN,
SEARCH
}
@@ -13,7 +13,8 @@ import com.owncloud.android.operations.DownloadFileOperation
sealed class WorkerState {
data class DownloadFinished(var currentFile: OCFile?) : WorkerState()
data class DownloadStarted(var user: User?, var currentDownload: DownloadFileOperation?) : WorkerState()
data class DownloadStarted(var user: User?, var currentDownload: DownloadFileOperation?, var percent: Int) :
WorkerState()
data class UploadFinished(var currentFile: OCFile?) : WorkerState()
data class UploadStarted(var user: User?) : WorkerState()
data object OfflineOperationsCompleted : WorkerState()
@@ -84,7 +84,6 @@ class ChooseAccountDialogFragment :
return builder.create()
}
@Suppress("LongMethod")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
accountManager = (activity as BaseActivity).userAccountManager
@@ -139,23 +138,13 @@ class ChooseAccountDialogFragment :
(activity as DrawerActivity).openManageAccounts()
}
binding.onlineStatus.setOnClickListener {
val setStatusDialog = SetOnlineStatusBottomSheet(currentStatus)
binding.setStatus.setOnClickListener {
val setStatusDialog = SetStatusDialogFragment.newInstance(accountManager.user, currentStatus)
setStatusDialog.show((activity as DrawerActivity).supportFragmentManager, "fragment_set_status")
dismiss()
}
binding.statusMessage.setOnClickListener {
val setStatusMessageDialog = SetStatusMessageBottomSheet(accountManager.user, currentStatus)
setStatusMessageDialog.show(
(activity as DrawerActivity).supportFragmentManager,
"fragment_set_status_message"
)
dismiss()
}
val capability = FileDataStorageManager(user, context?.contentResolver)
.getCapability(user)
@@ -184,10 +173,8 @@ class ChooseAccountDialogFragment :
viewThemeUtils.platform.themeDialogDivider(binding.separatorLine)
viewThemeUtils.platform.themeDialog(binding.root)
viewThemeUtils.material.colorMaterialTextButton(binding.onlineStatus)
viewThemeUtils.dialog.colorDialogMenuText(binding.onlineStatus)
viewThemeUtils.material.colorMaterialTextButton(binding.statusMessage)
viewThemeUtils.dialog.colorDialogMenuText(binding.statusMessage)
viewThemeUtils.material.colorMaterialTextButton(binding.setStatus)
viewThemeUtils.dialog.colorDialogMenuText(binding.setStatus)
viewThemeUtils.material.colorMaterialTextButton(binding.addAccount)
viewThemeUtils.dialog.colorDialogMenuText(binding.addAccount)
viewThemeUtils.material.colorMaterialTextButton(binding.manageAccounts)
@@ -1,160 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2020 Nextcloud GmbH
*
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
*/
package com.nextcloud.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.card.MaterialCardView
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.di.Injectable
import com.nextcloud.utils.extensions.setVisibleIf
import com.owncloud.android.R
import com.owncloud.android.databinding.SetOnlineStatusBottomSheetBinding
import com.owncloud.android.lib.resources.users.Status
import com.owncloud.android.lib.resources.users.StatusType
import com.owncloud.android.ui.activity.BaseActivity
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.theme.CapabilityUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
import javax.inject.Inject
class SetOnlineStatusBottomSheet(val currentStatus: Status?) :
BottomSheetDialogFragment(R.layout.set_online_status_bottom_sheet),
Injectable {
private lateinit var binding: SetOnlineStatusBottomSheetBinding
private lateinit var accountManager: UserAccountManager
@Inject
lateinit var asyncRunner: AsyncRunner
@Inject
lateinit var viewThemeUtils: ViewThemeUtils
@SuppressLint("DefaultLocale")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
accountManager = (activity as BaseActivity).userAccountManager
currentStatus?.let {
updateCurrentStatusViews(it)
}
binding.onlineStatus.setOnClickListener { setStatus(StatusType.ONLINE) }
binding.awayStatus.setOnClickListener { setStatus(StatusType.AWAY) }
binding.busyStatus.setOnClickListener { setStatus(StatusType.BUSY) }
binding.dndStatus.setOnClickListener { setStatus(StatusType.DND) }
binding.invisibleStatus.setOnClickListener { setStatus(StatusType.INVISIBLE) }
viewThemeUtils.files.themeStatusCardView(binding.onlineStatus)
viewThemeUtils.files.themeStatusCardView(binding.awayStatus)
viewThemeUtils.files.themeStatusCardView(binding.busyStatus)
viewThemeUtils.files.themeStatusCardView(binding.dndStatus)
viewThemeUtils.files.themeStatusCardView(binding.invisibleStatus)
viewThemeUtils.platform.themeDialog(binding.root)
binding.busyStatus.setVisibleIf(CapabilityUtils.getCapability(context).userStatusSupportsBusy.isTrue)
}
private fun updateCurrentStatusViews(it: Status) {
visualizeStatus(it.status)
}
private fun setStatus(statusType: StatusType) {
asyncRunner.postQuickTask(
SetStatusTask(
statusType,
accountManager.currentOwnCloudAccount?.savedAccount,
context
),
{
if (it) {
dismiss()
} else {
showErrorSnackbar()
}
},
{
showErrorSnackbar()
}
)
}
private fun showErrorSnackbar() {
DisplayUtils.showSnackMessage(view, "Failed to set status!")
clearTopStatus()
}
private fun visualizeStatus(statusType: StatusType) {
clearTopStatus()
val views: Triple<MaterialCardView, TextView, ImageView> = when (statusType) {
StatusType.ONLINE -> Triple(binding.onlineStatus, binding.onlineHeadline, binding.onlineIcon)
StatusType.AWAY -> Triple(binding.awayStatus, binding.awayHeadline, binding.awayIcon)
StatusType.BUSY -> Triple(binding.busyStatus, binding.busyHeadline, binding.busyIcon)
StatusType.DND -> Triple(binding.dndStatus, binding.dndHeadline, binding.dndIcon)
StatusType.INVISIBLE -> Triple(binding.invisibleStatus, binding.invisibleHeadline, binding.invisibleIcon)
else -> {
Log.d(TAG, "unknown status")
return
}
}
views.first.isChecked = true
viewThemeUtils.platform.colorOnSecondaryContainerTextViewElement(views.second)
}
private fun clearTopStatus() {
context?.let {
binding.onlineHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.awayHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.busyHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.dndHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.invisibleHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.awayIcon.imageTintList = null
binding.dndIcon.imageTintList = null
binding.invisibleIcon.imageTintList = null
binding.onlineStatus.isChecked = false
binding.awayStatus.isChecked = false
binding.busyStatus.isChecked = false
binding.dndStatus.isChecked = false
binding.invisibleStatus.isChecked = false
}
}
companion object {
private val TAG = SetOnlineStatusBottomSheet::class.simpleName
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = SetOnlineStatusBottomSheetBinding.inflate(layoutInflater, container, false)
return binding.root
}
}
@@ -10,8 +10,10 @@
package com.nextcloud.ui
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
@@ -19,21 +21,28 @@ import android.view.inputmethod.InputMethodManager
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.VisibleForTesting
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.card.MaterialCardView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.core.AsyncRunner
import com.nextcloud.client.di.Injectable
import com.nextcloud.client.network.ClientFactory
import com.nextcloud.utils.extensions.getParcelableArgument
import com.owncloud.android.R
import com.owncloud.android.databinding.SetStatusMessageBottomSheetBinding
import com.owncloud.android.databinding.DialogSetStatusBinding
import com.owncloud.android.datamodel.ArbitraryDataProvider
import com.owncloud.android.lib.resources.users.ClearAt
import com.owncloud.android.lib.resources.users.PredefinedStatus
import com.owncloud.android.lib.resources.users.Status
import com.owncloud.android.lib.resources.users.StatusType
import com.owncloud.android.ui.activity.BaseActivity
import com.owncloud.android.ui.adapter.PredefinedStatusClickListener
import com.owncloud.android.ui.adapter.PredefinedStatusListAdapter
@@ -48,6 +57,9 @@ import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
private const val ARG_CURRENT_USER_PARAM = "currentUser"
private const val ARG_CURRENT_STATUS_PARAM = "currentStatus"
private const val POS_DONT_CLEAR = 0
private const val POS_HALF_AN_HOUR = 1
private const val POS_AN_HOUR = 2
@@ -66,13 +78,15 @@ private const val LAST_SECOND_OF_MINUTE = 59
private const val CLEAR_AT_TYPE_PERIOD = "period"
private const val CLEAR_AT_TYPE_END_OF = "end-of"
class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
BottomSheetDialogFragment(R.layout.set_status_message_bottom_sheet),
class SetStatusDialogFragment :
DialogFragment(),
PredefinedStatusClickListener,
Injectable {
private lateinit var binding: SetStatusMessageBottomSheetBinding
private lateinit var binding: DialogSetStatusBinding
private var currentUser: User? = null
private var currentStatus: Status? = null
private lateinit var accountManager: UserAccountManager
private lateinit var predefinedStatus: ArrayList<PredefinedStatus>
private lateinit var adapter: PredefinedStatusListAdapter
@@ -86,22 +100,40 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
@Inject
lateinit var asyncRunner: AsyncRunner
@Inject
lateinit var clientFactory: ClientFactory
@Inject
lateinit var viewThemeUtils: ViewThemeUtils
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
currentUser = it.getParcelableArgument(ARG_CURRENT_USER_PARAM, User::class.java)
currentStatus = it.getParcelableArgument(ARG_CURRENT_STATUS_PARAM, Status::class.java)
val json = arbitraryDataProvider.getValue(user, ArbitraryDataProvider.PREDEFINED_STATUS)
val json = arbitraryDataProvider.getValue(currentUser, ArbitraryDataProvider.PREDEFINED_STATUS)
if (json.isNotEmpty()) {
val myType = object : TypeToken<ArrayList<PredefinedStatus>>() {}.type
predefinedStatus = Gson().fromJson(json, myType)
if (json.isNotEmpty()) {
val myType = object : TypeToken<ArrayList<PredefinedStatus>>() {}.type
predefinedStatus = Gson().fromJson(json, myType)
}
}
EmojiManager.install(GoogleEmojiProvider())
}
@SuppressLint("InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
binding = DialogSetStatusBinding.inflate(layoutInflater)
val builder = MaterialAlertDialogBuilder(requireContext()).setView(binding.root)
viewThemeUtils.dialog.colorMaterialAlertDialogBackground(binding.statusView.context, builder)
return builder.create()
}
@SuppressLint("DefaultLocale")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
@@ -118,6 +150,16 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
binding.predefinedStatusList.adapter = adapter
binding.predefinedStatusList.layoutManager = LinearLayoutManager(context)
binding.onlineStatus.setOnClickListener { setStatus(StatusType.ONLINE) }
binding.dndStatus.setOnClickListener { setStatus(StatusType.DND) }
binding.awayStatus.setOnClickListener { setStatus(StatusType.AWAY) }
binding.invisibleStatus.setOnClickListener { setStatus(StatusType.INVISIBLE) }
viewThemeUtils.files.themeStatusCardView(binding.onlineStatus)
viewThemeUtils.files.themeStatusCardView(binding.dndStatus)
viewThemeUtils.files.themeStatusCardView(binding.awayStatus)
viewThemeUtils.files.themeStatusCardView(binding.invisibleStatus)
binding.clearStatus.setOnClickListener { clearStatus() }
binding.setStatus.setOnClickListener { setStatusMessage() }
binding.emoji.setOnClickListener { popup.show() }
@@ -162,19 +204,15 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
}
private fun updateCurrentStatusViews(it: Status) {
if (it.icon.isNullOrBlank()) {
binding.emoji.setText("😀")
} else {
binding.emoji.setText(it.icon)
}
binding.emoji.setText(it.icon)
binding.customStatusInput.text?.clear()
binding.customStatusInput.setText(it.message)
visualizeStatus(it.status)
if (it.clearAt > 0) {
binding.clearStatusAfterSpinner.visibility = View.GONE
binding.remainingClearTime.apply {
binding.clearStatusMessageTextView.text = getString(R.string.clear)
binding.clearStatusMessageTextView.text = getString(R.string.clear_status_message)
visibility = View.VISIBLE
text = DisplayUtils.getRelativeTimestamp(context, it.clearAt * ONE_SECOND_IN_MILLIS, true)
.toString()
@@ -182,7 +220,7 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
setOnClickListener {
visibility = View.GONE
binding.clearStatusAfterSpinner.visibility = View.VISIBLE
binding.clearStatusMessageTextView.text = getString(R.string.clear_status_after)
binding.clearStatusMessageTextView.text = getString(R.string.clear_status_message_after)
}
}
}
@@ -195,24 +233,20 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
// 30 minutes
System.currentTimeMillis() / ONE_SECOND_IN_MILLIS + THIRTY_MINUTES * ONE_MINUTE_IN_SECONDS
}
POS_AN_HOUR -> {
// one hour
System.currentTimeMillis() / ONE_SECOND_IN_MILLIS + ONE_MINUTE_IN_SECONDS * ONE_MINUTE_IN_SECONDS
}
POS_FOUR_HOURS -> {
// four hours
System.currentTimeMillis() / ONE_SECOND_IN_MILLIS +
FOUR_HOURS * ONE_MINUTE_IN_SECONDS * ONE_MINUTE_IN_SECONDS
}
POS_TODAY -> {
// today
val date = getLastSecondOfToday()
dateToSeconds(date)
}
POS_END_OF_WEEK -> {
// end of week
val date = getLastSecondOfToday()
@@ -221,7 +255,6 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
}
dateToSeconds(date)
}
else -> clearAt
}
}
@@ -230,12 +263,10 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
clearAt?.type == CLEAR_AT_TYPE_PERIOD -> {
System.currentTimeMillis() / ONE_SECOND_IN_MILLIS + clearAt.time.toLong()
}
clearAt?.type == CLEAR_AT_TYPE_END_OF && clearAt.time == "day" -> {
val date = getLastSecondOfToday()
dateToSeconds(date)
}
else -> -1
}
@@ -257,6 +288,67 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
)
}
private fun setStatus(statusType: StatusType) {
visualizeStatus(statusType)
asyncRunner.postQuickTask(
SetStatusTask(
statusType,
accountManager.currentOwnCloudAccount?.savedAccount,
context
),
{
if (!it) {
clearTopStatus()
}
},
{ clearTopStatus() }
)
}
private fun visualizeStatus(statusType: StatusType) {
clearTopStatus()
val views: Triple<MaterialCardView, TextView, ImageView> = when (statusType) {
StatusType.ONLINE -> Triple(binding.onlineStatus, binding.onlineHeadline, binding.onlineIcon)
StatusType.AWAY -> Triple(binding.awayStatus, binding.awayHeadline, binding.awayIcon)
StatusType.DND -> Triple(binding.dndStatus, binding.dndHeadline, binding.dndIcon)
StatusType.INVISIBLE -> Triple(binding.invisibleStatus, binding.invisibleHeadline, binding.invisibleIcon)
else -> {
Log.d(TAG, "unknown status")
return
}
}
views.first.isChecked = true
viewThemeUtils.platform.colorOnSecondaryContainerTextViewElement(views.second)
}
private fun clearTopStatus() {
context?.let {
binding.onlineHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.awayHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.dndHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.invisibleHeadline.setTextColor(
resources.getColor(com.nextcloud.android.common.ui.R.color.high_emphasis_text)
)
binding.onlineIcon.imageTintList = null
binding.awayIcon.imageTintList = null
binding.dndIcon.imageTintList = null
binding.invisibleIcon.imageTintList = null
binding.onlineStatus.isChecked = false
binding.awayStatus.isChecked = false
binding.dndStatus.isChecked = false
binding.invisibleStatus.isChecked = false
}
}
private fun setStatusMessage() {
if (selectedPredefinedMessageId != null) {
asyncRunner.postQuickTask(
@@ -285,16 +377,29 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
private fun dismiss(boolean: Boolean) {
if (boolean) {
dismiss()
} else {
DisplayUtils.showSnackMessage(view, view?.resources?.getString(R.string.error_setting_status_message))
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = SetStatusMessageBottomSheetBinding.inflate(layoutInflater, container, false)
return binding.root
/**
* Fragment creator
*/
companion object {
private val TAG = SetStatusDialogFragment::class.simpleName
@JvmStatic
fun newInstance(user: User, status: Status?): SetStatusDialogFragment {
val args = Bundle()
args.putParcelable(ARG_CURRENT_USER_PARAM, user)
args.putParcelable(ARG_CURRENT_STATUS_PARAM, status)
val dialogFragment = SetStatusDialogFragment()
dialogFragment.arguments = args
return dialogFragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
binding.root
override fun onClick(predefinedStatus: PredefinedStatus) {
selectedPredefinedMessageId = predefinedStatus.id
clearAt = clearAtToUnixTime(predefinedStatus.clearAt)
@@ -304,7 +409,7 @@ class SetStatusMessageBottomSheet(val user: User, val currentStatus: Status?) :
binding.remainingClearTime.visibility = View.GONE
binding.clearStatusAfterSpinner.visibility = View.VISIBLE
binding.clearStatusMessageTextView.text = getString(R.string.clear_status_after)
binding.clearStatusMessageTextView.text = getString(R.string.clear_status_message_after)
val clearAt = predefinedStatus.clearAt
if (clearAt == null) {
@@ -1,36 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.ui.behavior
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.google.android.material.behavior.HideViewOnScrollBehavior
class OnScrollBehavior<V : View> @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
HideViewOnScrollBehavior<V>(context, attrs) {
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: V,
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int,
consumed: IntArray
) {
if (dyConsumed > 0) {
slideOut(child)
} else if (dyConsumed < 0 || dyUnconsumed < 0) {
slideIn(child)
}
}
}
@@ -39,8 +39,8 @@ enum class FileAction(
// Uploads and downloads
DOWNLOAD_FILE(R.id.action_download_file, R.string.filedetails_download, R.drawable.ic_cloud_download),
DOWNLOAD_FOLDER(R.id.action_sync_file, R.string.filedetails_sync_file, R.drawable.ic_sync),
CANCEL_SYNC(R.id.action_cancel_sync, R.string.common_cancel_sync, R.drawable.ic_sync_off),
SYNC_FILE(R.id.action_sync_file, R.string.filedetails_sync_file, R.drawable.ic_cloud_sync_on),
CANCEL_SYNC(R.id.action_cancel_sync, R.string.common_cancel_sync, R.drawable.ic_cloud_sync_off),
// File sharing
EXPORT_FILE(R.id.action_export_file, R.string.filedetails_export, R.drawable.ic_export),
@@ -84,7 +84,7 @@ enum class FileAction(
SEND_SHARE_FILE,
SEND_FILE,
OPEN_FILE_WITH,
DOWNLOAD_FOLDER,
SYNC_FILE,
CANCEL_SYNC,
SELECT_ALL,
SELECT_NONE,
@@ -206,18 +206,6 @@ enum class FileAction(
result.add(R.id.action_edit)
}
if (files.any { it.isRecommendedFile }) {
val allowedForRecommended = setOf(
R.id.action_see_details,
R.id.action_set_as_wallpaper,
R.id.action_pin_to_homescreen,
R.id.action_open_file_with
)
val allActions = entries.map { it.id }
result.addAll(allActions - allowedForRecommended)
}
return result
}
@@ -33,7 +33,6 @@ import com.nextcloud.android.common.ui.theme.utils.ColorRole
import com.nextcloud.client.account.CurrentAccountProvider
import com.nextcloud.client.di.Injectable
import com.nextcloud.client.di.ViewModelFactory
import com.nextcloud.utils.extensions.setVisibleIf
import com.owncloud.android.R
import com.owncloud.android.databinding.FileActionsBottomSheetBinding
import com.owncloud.android.databinding.FileActionsBottomSheetItemBinding
@@ -45,7 +44,6 @@ import com.owncloud.android.lib.resources.files.model.FileLockType
import com.owncloud.android.ui.activity.ComponentsGetter
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.DisplayUtils.AvatarGenerationListener
import com.owncloud.android.utils.FileStorageUtils
import com.owncloud.android.utils.theme.ViewThemeUtils
import javax.inject.Inject
@@ -206,23 +204,11 @@ class FileActionsBottomSheet :
private fun displayTitle(titleFile: OCFile?) {
val decryptedFileName = titleFile?.decryptedFileName
if (decryptedFileName != null) {
val isFolder = titleFile.isFolder
val isRTL = DisplayUtils.isRTL()
val (base, ext) = FileStorageUtils.getFilenameAndExtension(decryptedFileName, isFolder, isRTL)
val titleMaxWidth = DisplayUtils.convertDpToPixel(
requireContext().resources.configuration.screenWidthDp.times(FILENAME_MAX_WIDTH_PERCENTAGE).toFloat(),
context
)
binding.title.maxWidth = titleMaxWidth
binding.title.text = base
binding.extension.setVisibleIf(!isFolder)
if (!isFolder) {
binding.extension.text = ext
decryptedFileName.let {
binding.title.text = it
}
} else {
binding.title.isVisible = false
binding.extension.isVisible = false
}
}
@@ -314,7 +300,6 @@ class FileActionsBottomSheet :
companion object {
private const val REQUEST_KEY = "REQUEST_KEY_ACTION"
private const val RESULT_KEY_ACTION_ID = "RESULT_KEY_ACTION_ID"
private const val FILENAME_MAX_WIDTH_PERCENTAGE = 0.6
@JvmStatic
@JvmOverloads
@@ -8,10 +8,7 @@
package com.nextcloud.utils
import android.graphics.Bitmap
import android.graphics.Matrix
import androidx.core.graphics.scale
import androidx.exifinterface.media.ExifInterface
import com.owncloud.android.lib.common.utils.Log_OC
@Suppress("MagicNumber")
fun Bitmap.allocationKilobyte(): Int = allocationByteCount.div(1024)
@@ -41,79 +38,3 @@ fun Bitmap.scaleUntil(targetKB: Int): Bitmap {
val scaledBitmap = scale(width, height)
return scaledBitmap.scaleUntil(targetKB)
}
/**
* Rotates and/or flips a [Bitmap] according to an EXIF orientation constant.
*
* Needed because loading bitmaps directly may ignore EXIF metadata with some devices,
* resulting in incorrectly displayed images.
*
* This function uses a [Matrix] transformation to adjust the image so that it
* appears upright when displayed. It supports all standard EXIF orientations,
* including mirrored and rotated cases.
*
* The original bitmap will be recycled if a new one is successfully created.
* If the device runs out of memory during the transformation, the original bitmap
* is returned unchanged.
*
* @receiver The [Bitmap] to rotate or flip. Can be `null`.
* @param orientation One of the [ExifInterface] orientation constants, such as
* [ExifInterface.ORIENTATION_ROTATE_90] or [ExifInterface.ORIENTATION_FLIP_HORIZONTAL].
* @return The correctly oriented [Bitmap], or `null` if the receiver was `null`.
*
* @see ExifInterface
* @see Matrix
*/
@Suppress("MagicNumber", "ReturnCount")
fun Bitmap?.rotateBitmapViaExif(orientation: Int): Bitmap? {
if (this == null) {
return null
}
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return this
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return this
}
return try {
val rotated = Bitmap.createBitmap(
this,
0,
0,
this.width,
this.height,
matrix,
true
)
// release original if a new one was created
if (rotated != this) {
this.recycle()
}
rotated
} catch (_: OutOfMemoryError) {
Log_OC.e("BitmapExtension", "rotating bitmap, out of memory exception")
this
}
}
@@ -1,67 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <alper.ozturk@nextcloud.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils
import com.owncloud.android.lib.common.utils.Log_OC
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors
import kotlin.io.path.pathString
@Suppress("NestedBlockDepth")
object FileHelper {
private const val TAG = "FileHelper"
fun listDirectoryEntries(directory: File?, startIndex: Int, maxItems: Int, fetchFolders: Boolean): List<File> {
if (directory == null || !directory.exists() || !directory.isDirectory) return emptyList()
return try {
Files.list(directory.toPath())
.map { it.toFile() }
.filter { file -> if (fetchFolders) file.isDirectory else !file.isDirectory }
.skip(startIndex.toLong())
.limit(maxItems.toLong())
.collect(Collectors.toList())
} catch (e: IOException) {
Log_OC.d(TAG, "listDirectoryEntries: $e")
emptyList()
}
}
fun listFilesRecursive(files: Collection<File>): List<String> {
val result = mutableListOf<String>()
for (file in files) {
try {
collectFilesRecursively(file.toPath(), result)
} catch (e: IOException) {
Log_OC.e(TAG, "Error collecting files recursively from: ${file.absolutePath}", e)
}
}
return result
}
private fun collectFilesRecursively(path: Path, result: MutableList<String>) {
if (Files.isDirectory(path)) {
try {
Files.newDirectoryStream(path).use { stream ->
for (entry in stream) {
collectFilesRecursively(entry, result)
}
}
} catch (e: IOException) {
Log_OC.e(TAG, "Error reading directory: ${path.pathString}", e)
}
} else {
result.add(path.pathString)
}
}
}
Loaded 100 of 380 files, more files were not shown because too many files have changed in this diff. Show more