Compare commits
215
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00e628a5b1 | ||
|
|
ac7d82a7f0 | ||
|
|
27340def2c | ||
|
|
e8a8a82671 | ||
|
|
416e2b80f8 | ||
|
|
176577aae8 | ||
|
|
2500a692a7 | ||
|
|
076972789e | ||
|
|
0c737e04c5 | ||
|
|
46d1253210 | ||
|
|
2719530f7a | ||
|
|
72ff3a5f26 | ||
|
|
0028b6f0fd | ||
|
|
e77b10ebdc | ||
|
|
88fc3f362b | ||
|
|
1d19cc6992 | ||
|
|
d831a8b96d | ||
|
|
3453a7a1f3 | ||
|
|
2f58e63b45 | ||
|
|
cbe2e9e433 | ||
|
|
17e6e553e5 | ||
|
|
4453eaf5d3 | ||
|
|
21e0c82e65 | ||
|
|
7a5f707e9a | ||
|
|
cbe4932b85 | ||
|
|
be2b8416da | ||
|
|
57acd7d046 | ||
|
|
622e22f801 | ||
|
|
8bc660e9b0 | ||
|
|
b431522ceb | ||
|
|
aa5d00dc85 | ||
|
|
675017c0b7 | ||
|
|
79f3938a10 | ||
|
|
55ee6af50c | ||
|
|
02684cb212 | ||
|
|
8169857a28 | ||
|
|
145b79633e | ||
|
|
eb6282f885 | ||
|
|
a66095eead | ||
|
|
5cc8c43531 | ||
|
|
1036b44975 | ||
|
|
8510970467 | ||
|
|
782adad8a5 | ||
|
|
f3df1dd4f5 | ||
|
|
94fed2aa62 | ||
|
|
bca8dae206 | ||
|
|
a7f42e8caa | ||
|
|
8a315b9f9f | ||
|
|
bcbc089094 | ||
|
|
2fbf25e765 | ||
|
|
4e0c1083bb | ||
|
|
1ae05df898 | ||
|
|
699cbc525b | ||
|
|
e1a80b64f4 | ||
|
|
52bb721afc | ||
|
|
bb1782e7cc | ||
|
|
004f14ea7f | ||
|
|
b1d842c6f6 | ||
|
|
f5acb815b3 | ||
|
|
feed19eea4 | ||
|
|
7dbfa0d551 | ||
|
|
a222d55b0c | ||
|
|
16996c7601 | ||
|
|
3a3072612d | ||
|
|
f7dee5449f | ||
|
|
f1434d833d | ||
|
|
195c398ca4 | ||
|
|
5a86c0f00a | ||
|
|
db0d113b52 | ||
|
|
8fac856d87 | ||
|
|
083c393c0b | ||
|
|
07e81c2c87 | ||
|
|
5b9a7d291b | ||
|
|
3bb1c7f4d8 | ||
|
|
7e9c8ccbfc | ||
|
|
3686edd55c | ||
|
|
62a51e4063 | ||
|
|
5b11ed7b20 | ||
|
|
4e9247a130 | ||
|
|
81296dcf8b | ||
|
|
a704326574 | ||
|
|
3cab716a97 | ||
|
|
596264d5cd | ||
|
|
50d4b8d187 | ||
|
|
cf5cbb1635 | ||
|
|
a71c7fd1d9 | ||
|
|
ea3d6407c5 | ||
|
|
b4bba97efc | ||
|
|
84be18b5fb | ||
|
|
2a64e26c10 | ||
|
|
67a638ad4e | ||
|
|
8f4096e6dc | ||
|
|
a26beacc40 | ||
|
|
1a40920dd7 | ||
|
|
6de9b48fd3 | ||
|
|
1000c82d5e | ||
|
|
f03f517593 | ||
|
|
3155c65a74 | ||
|
|
7e1880c3de | ||
|
|
794d48e665 | ||
|
|
5d033e7986 | ||
|
|
279b5fa209 | ||
|
|
d562e5feb3 | ||
|
|
18481f45d7 | ||
|
|
683ed9b0b8 | ||
|
|
d4e131e81f | ||
|
|
484fe04245 | ||
|
|
b0f429b477 | ||
|
|
13f40c4026 | ||
|
|
2ea35f2f0b | ||
|
|
9e4197e4b9 | ||
|
|
7a021f4be9 | ||
|
|
03c22ee4a0 | ||
|
|
4fbaaa307d | ||
|
|
7275d8b14e | ||
|
|
199e754e9b | ||
|
|
db028503d9 | ||
|
|
8a028567d1 | ||
|
|
7a97e558c3 | ||
|
|
b83ac7d6a4 | ||
|
|
6bdbbcb0d7 | ||
|
|
45a5e6bd26 | ||
|
|
8d2182a29e | ||
|
|
5479c135eb | ||
|
|
3c5aaad6d6 | ||
|
|
eb13420f35 | ||
|
|
26158aba2c | ||
|
|
c89832b1ff | ||
|
|
6e3f63d4d4 | ||
|
|
eedd3473f5 | ||
|
|
5ebb4cfad2 | ||
|
|
8baa0a6988 | ||
|
|
1f900b7a55 | ||
|
|
c18278b973 | ||
|
|
7fe00834ed | ||
|
|
83d3cfba1d | ||
|
|
30e67b530f | ||
|
|
a4eb0c9275 | ||
|
|
39a7aff33c | ||
|
|
07e7484c5a | ||
|
|
a1ce48da06 | ||
|
|
8dd522d600 | ||
|
|
b489ddae99 | ||
|
|
80552ca895 | ||
|
|
e6aa4471b8 | ||
|
|
79d2ed8889 | ||
|
|
2a6ba436aa | ||
|
|
4e9f63873c | ||
|
|
895fd68e84 | ||
|
|
614bacc074 | ||
|
|
e7d0c1d0ec | ||
|
|
fc927e7bac | ||
|
|
d52dbb705c | ||
|
|
ea07d3c5ee | ||
|
|
50fc0d3d7f | ||
|
|
1587631797 | ||
|
|
3f9ed092df | ||
|
|
63f6edc1d4 | ||
|
|
0f237fc3dc | ||
|
|
0776265f6d | ||
|
|
312be7b171 | ||
|
|
3b26d54de5 | ||
|
|
1ba667e925 | ||
|
|
1bc0e70453 | ||
|
|
1be313a21c | ||
|
|
37e936b19a | ||
|
|
3aaf7603f9 | ||
|
|
f6c790f13c | ||
|
|
f0ebd7d2c7 | ||
|
|
e307143074 | ||
|
|
f5b288b59f | ||
|
|
bef0cfa885 | ||
|
|
5e895ec306 | ||
|
|
9122d0a261 | ||
|
|
98c4ea9c77 | ||
|
|
a1aa3a5455 | ||
|
|
20ea984885 | ||
|
|
5dbe8d5eab | ||
|
|
d267d4cb2c | ||
|
|
24a11c5e5e | ||
|
|
f639788ebc | ||
|
|
b622174c95 | ||
|
|
31fa1c4413 | ||
|
|
2f6b724540 | ||
|
|
0814e10937 | ||
|
|
18e9019a14 | ||
|
|
86e35bc871 | ||
|
|
a85379bafb | ||
|
|
d1d06c144f | ||
|
|
7352fa05e4 | ||
|
|
fad3ed061f | ||
|
|
b90110b605 | ||
|
|
5d5e5106d1 | ||
|
|
032e906778 | ||
|
|
84de8e64c4 | ||
|
|
4f873754f8 | ||
|
|
7531426c0b | ||
|
|
65e93d8500 | ||
|
|
f065874a96 | ||
|
|
1956e0e582 | ||
|
|
e1877d0cb4 | ||
|
|
505d6b72ac | ||
|
|
74a5282dbb | ||
|
|
94a1a7e34d | ||
|
|
2cbda4ed42 | ||
|
|
9c80a480f4 | ||
|
|
af76c5c9b6 | ||
|
|
4503d4431e | ||
|
|
29a0956614 | ||
|
|
1c7749bcb4 | ||
|
|
93d4244859 | ||
|
|
726fcbc8e4 | ||
|
|
aab2051f5f | ||
|
|
7a80da65cb | ||
|
|
b7b250bb2f |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
FROM ubuntu:noble@sha256:353675e2a41babd526e2b837d7ec780c2a05bca0164f7ea5dbbd433d21d166fc
|
||||
FROM ubuntu:noble@sha256:66460d557b25769b102175144d538d88219c077c678a49af4afca6fbfc1b5252
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV ANDROID_HOME=/usr/lib/android-sdk
|
||||
|
||||
@@ -27,6 +27,7 @@ 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 }}
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
- uses: gradle/actions/wrapper-validation@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
- uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
- name: Build ${{ matrix.flavor }}
|
||||
run: |
|
||||
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
with:
|
||||
swap-size-gb: 10
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
|
||||
uses: github/codeql-action/init@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
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@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
|
||||
uses: github/codeql-action/analyze@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
@@ -24,4 +24,4 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: REUSE Compliance Check
|
||||
uses: fsfe/reuse-action@bb774aa972c2a89ff34781233d275075cbddf542 # v5.0.0
|
||||
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
|
||||
@@ -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@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
|
||||
uses: github/codeql-action/upload-sarif@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
|
||||
with:
|
||||
sarif_file: results.sarif
|
||||
@@ -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@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
name: Report-${{ matrix.color }}-${{ matrix.scheme }}
|
||||
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
if: ${{ always() }}
|
||||
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
- name: Run unit tests with coverage
|
||||
run: ./gradlew jacocoTestGplayDebugUnitTest
|
||||
- name: Upload failing results
|
||||
@@ -49,7 +49,7 @@ jobs:
|
||||
fail_ci_if_error: true
|
||||
- name: Upload jacoco artifacts
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||
with:
|
||||
name: test-results
|
||||
path: app/build/reports/tests/testGplayDebugUnitTest/
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
<!--
|
||||
~ SPDX-FileCopyrightText: 2025 Saeed <[email protected]>
|
||||
~ SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
-->
|
||||
# تطبيق [Nextcloud](https://nextcloud.com)لأجهزة أندرويد 📱
|
||||
|
||||
[](https://api.reuse.software/info/github.com/nextcloud/android)
|
||||
[](https://drone.nextcloud.com/nextcloud/android)
|
||||
[](https://app.codacy.com/gh/nextcloud/android/dashboard)
|
||||
[](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 حاليًا.
|
||||
+3
-2
@@ -116,8 +116,8 @@ android {
|
||||
defaultConfig {
|
||||
applicationId = "com.nextcloud.client"
|
||||
minSdk = 27
|
||||
targetSdk = 35
|
||||
compileSdk = 35
|
||||
targetSdk = 36
|
||||
compileSdk = 36
|
||||
|
||||
buildConfigField "boolean", "CI", ciBuild.toString()
|
||||
buildConfigField "boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString()
|
||||
@@ -296,6 +296,7 @@ dependencies {
|
||||
|
||||
// region 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)
|
||||
|
||||
@@ -119,7 +119,8 @@ class SyncedFoldersActivityIT : AbstractIT() {
|
||||
onIdleSync {
|
||||
EspressoIdlingResource.increment()
|
||||
val dialog = sut.buildPowerCheckDialog()
|
||||
dialog.show()
|
||||
sut.showPowerCheckDialog()
|
||||
|
||||
EspressoIdlingResource.decrement()
|
||||
|
||||
val screenShotName = createName(testClassName + "_" + "showPowerCheckDialog", "")
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/*
|
||||
* 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)
|
||||
}
|
||||
}
|
||||
+5
-7
@@ -18,6 +18,7 @@ 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;
|
||||
@@ -108,7 +109,7 @@ public class UploadStorageManagerTest extends AbstractIT {
|
||||
OCUpload upload = createUpload(account);
|
||||
|
||||
uploads.add(upload);
|
||||
uploadsStorageManager.storeUpload(upload);
|
||||
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
|
||||
}
|
||||
|
||||
OCUpload[] storedUploads = uploadsStorageManager.getAllStoredUploads();
|
||||
@@ -151,17 +152,14 @@ public class UploadStorageManagerTest extends AbstractIT {
|
||||
account.name);
|
||||
|
||||
corruptUpload.setLocalPath(null);
|
||||
|
||||
uploadsStorageManager.storeUpload(corruptUpload);
|
||||
|
||||
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(corruptUpload));
|
||||
uploadsStorageManager.getAllStoredUploads();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getById() {
|
||||
OCUpload upload = createUpload(account);
|
||||
long id = uploadsStorageManager.storeUpload(upload);
|
||||
|
||||
long id = uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
|
||||
OCUpload newUpload = uploadsStorageManager.getUploadById(id);
|
||||
|
||||
assertNotNull(newUpload);
|
||||
@@ -178,7 +176,7 @@ public class UploadStorageManagerTest extends AbstractIT {
|
||||
|
||||
private void insertUploads(Account account, int rowsToInsert) {
|
||||
for (int i = 0; i < rowsToInsert; i++) {
|
||||
uploadsStorageManager.storeUpload(createUpload(account));
|
||||
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(createUpload(account)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -27,8 +27,8 @@ public class FileDisplayActivityTest extends AbstractIT {
|
||||
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
|
||||
Activity activity =
|
||||
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED).iterator().next();
|
||||
if (activity instanceof WhatsNewActivity) {
|
||||
activity.onBackPressed();
|
||||
if (activity instanceof WhatsNewActivity whatsNewActivity) {
|
||||
whatsNewActivity.getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
});
|
||||
scenario.recreate();
|
||||
|
||||
+1
-1
@@ -822,7 +822,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
|
||||
val processFragment =
|
||||
activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG) as
|
||||
FileDetailsSharingProcessFragment
|
||||
processFragment.onBackPressed()
|
||||
processFragment.activity?.onBackPressedDispatcher?.onBackPressed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:supportsRtl="true"
|
||||
android:enableOnBackInvokedCallback="false"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:theme="@style/Theme.ownCloud.Toolbar"
|
||||
android:usesCleartextTraffic="true"
|
||||
tools:ignore="UnusedAttribute"
|
||||
@@ -353,6 +353,7 @@
|
||||
<activity
|
||||
android:name=".ui.activity.SettingsActivity"
|
||||
android:exported="false"
|
||||
android:enableOnBackInvokedCallback="false"
|
||||
android:theme="@style/PreferenceTheme" />
|
||||
<activity
|
||||
android:name=".ui.preview.PreviewImageActivity"
|
||||
@@ -584,6 +585,8 @@
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver" android:exported="false" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.activity.CopyToClipboardActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -20,6 +20,7 @@ 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
|
||||
@@ -96,6 +97,7 @@ abstract class NextcloudDatabase : RoomDatabase() {
|
||||
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
|
||||
|
||||
@@ -17,15 +17,6 @@ import com.owncloud.android.utils.MimeType
|
||||
@Suppress("TooManyFunctions")
|
||||
@Dao
|
||||
interface FileDao {
|
||||
@Query(
|
||||
"""
|
||||
SELECT DISTINCT parent
|
||||
FROM filelist
|
||||
WHERE path IN (:subfilePaths)
|
||||
"""
|
||||
)
|
||||
fun getParentIdsOfSubfiles(subfilePaths: List<String>): List<Long>
|
||||
|
||||
@Update
|
||||
fun update(entity: FileEntity)
|
||||
|
||||
|
||||
@@ -9,21 +9,24 @@ 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 ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH}
|
||||
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 getAutoUploadFiles(syncedFolderId: String): List<String>
|
||||
suspend fun getAutoUploadFilesEntities(syncedFolderId: String, limit: Int, lastId: Int): List<FilesystemEntity>
|
||||
|
||||
@Query(
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* 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,6 +8,8 @@
|
||||
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
|
||||
@@ -27,4 +29,52 @@ interface UploadDao {
|
||||
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>
|
||||
}
|
||||
@@ -10,6 +10,9 @@ 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)
|
||||
@@ -50,3 +53,40 @@ 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,6 +1,7 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
|
||||
@@ -78,3 +79,33 @@ fun UploadEntity.toOCUpload(capability: OCCapability? = null): OCUpload {
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ 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;
|
||||
@@ -75,6 +76,8 @@ public interface AppComponent {
|
||||
|
||||
void inject(OfflineOperationReceiver offlineOperationReceiver);
|
||||
|
||||
void inject(FolderDownloadWorkerReceiver folderDownloadWorkerReceiver);
|
||||
|
||||
@Component.Builder
|
||||
interface Builder {
|
||||
@BindsInstance
|
||||
|
||||
@@ -104,7 +104,7 @@ class DocumentScanActivity :
|
||||
true
|
||||
}
|
||||
android.R.id.home -> {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
|
||||
@@ -10,6 +10,7 @@ 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
|
||||
@@ -46,6 +47,7 @@ class EtmActivity :
|
||||
onPageChanged(it)
|
||||
}
|
||||
)
|
||||
handleOnBackPressed()
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
|
||||
@@ -58,11 +60,17 @@ class EtmActivity :
|
||||
else -> super.onOptionsItemSelected(item)
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onBackPressed() {
|
||||
if (!vm.onBackPressed()) {
|
||||
super.onBackPressed()
|
||||
}
|
||||
private fun handleOnBackPressed() {
|
||||
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
val handledByVm = vm.onBackPressed()
|
||||
|
||||
if (!handledByVm) {
|
||||
isEnabled = false
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun onPageChanged(page: EtmMenuEntry?) {
|
||||
|
||||
@@ -17,14 +17,17 @@ 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.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
|
||||
@@ -61,7 +64,8 @@ class BackgroundJobFactory @Inject constructor(
|
||||
private val viewThemeUtils: Provider<ViewThemeUtils>,
|
||||
private val localBroadcastManager: Provider<LocalBroadcastManager>,
|
||||
private val generatePdfUseCase: GeneratePDFUseCase,
|
||||
private val syncedFolderProvider: SyncedFolderProvider
|
||||
private val syncedFolderProvider: SyncedFolderProvider,
|
||||
private val database: NextcloudDatabase
|
||||
) : WorkerFactory() {
|
||||
|
||||
@SuppressLint("NewApi")
|
||||
@@ -99,6 +103,7 @@ class BackgroundJobFactory @Inject constructor(
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -173,7 +178,8 @@ class BackgroundJobFactory @Inject constructor(
|
||||
connectivityService = connectivityService,
|
||||
powerManagementService = powerManagementService,
|
||||
syncedFolderProvider = syncedFolderProvider,
|
||||
backgroundJobManager = backgroundJobManager.get()
|
||||
backgroundJobManager = backgroundJobManager.get(),
|
||||
repository = FileSystemRepository(dao = database.fileSystemDao())
|
||||
)
|
||||
|
||||
private fun createOfflineSyncWork(context: Context, params: WorkerParameters): OfflineSyncWork = OfflineSyncWork(
|
||||
@@ -283,4 +289,12 @@ class BackgroundJobFactory @Inject constructor(
|
||||
params,
|
||||
accountManager.user
|
||||
)
|
||||
|
||||
private fun createFolderDownloadWorker(context: Context, params: WorkerParameters): FolderDownloadWorker =
|
||||
FolderDownloadWorker(
|
||||
accountManager,
|
||||
context,
|
||||
viewThemeUtils.get(),
|
||||
params
|
||||
)
|
||||
}
|
||||
@@ -122,13 +122,10 @@ interface BackgroundJobManager {
|
||||
|
||||
fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder)
|
||||
|
||||
/**
|
||||
* Immediately start File Sync job for given syncFolderID.
|
||||
*/
|
||||
fun startImmediateFilesSyncJob(
|
||||
fun startAutoUploadImmediately(
|
||||
syncedFolder: SyncedFolder,
|
||||
overridePowerSaving: Boolean = false,
|
||||
changedFiles: Array<String?> = arrayOf()
|
||||
contentUris: Array<String?> = arrayOf()
|
||||
)
|
||||
|
||||
fun cancelTwoWaySyncJob()
|
||||
@@ -143,12 +140,10 @@ interface BackgroundJobManager {
|
||||
fun startFilesUploadJob(user: User, uploadIds: LongArray, showSameFileAlreadyExistsNotification: Boolean)
|
||||
fun getFileUploads(user: User): LiveData<List<JobInfo>>
|
||||
fun cancelFilesUploadJob(user: User)
|
||||
fun isStartFileUploadJobScheduled(user: User): Boolean
|
||||
fun isStartFileUploadJobScheduled(accountName: String): Boolean
|
||||
|
||||
fun cancelFilesDownloadJob(user: User, fileId: Long)
|
||||
|
||||
fun isStartFileDownloadJobScheduled(user: User, fileId: Long): Boolean
|
||||
|
||||
@Suppress("LongParameterList")
|
||||
fun startFileDownloadJob(
|
||||
user: User,
|
||||
@@ -176,4 +171,6 @@ interface BackgroundJobManager {
|
||||
fun scheduleInternal2WaySync(intervalMinutes: Long)
|
||||
fun cancelAllFilesDownloadJobs()
|
||||
fun startMetadataSyncJob(currentDirPath: String)
|
||||
fun downloadFolder(folder: OCFile, accountName: String)
|
||||
fun cancelFolderDownload()
|
||||
}
|
||||
@@ -28,6 +28,7 @@ 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
|
||||
@@ -93,6 +94,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"
|
||||
|
||||
@@ -507,16 +509,16 @@ internal class BackgroundJobManagerImpl(
|
||||
)
|
||||
}
|
||||
|
||||
override fun startImmediateFilesSyncJob(
|
||||
override fun startAutoUploadImmediately(
|
||||
syncedFolder: SyncedFolder,
|
||||
overridePowerSaving: Boolean,
|
||||
changedFiles: Array<String?>
|
||||
contentUris: Array<String?>
|
||||
) {
|
||||
val syncedFolderID = syncedFolder.id
|
||||
|
||||
val arguments = Data.Builder()
|
||||
.putBoolean(AutoUploadWorker.OVERRIDE_POWER_SAVING, overridePowerSaving)
|
||||
.putStringArray(AutoUploadWorker.CHANGED_FILES, changedFiles)
|
||||
.putStringArray(AutoUploadWorker.CONTENT_URIS, contentUris)
|
||||
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
|
||||
.build()
|
||||
|
||||
@@ -635,10 +637,10 @@ internal class BackgroundJobManagerImpl(
|
||||
workManager.enqueue(request)
|
||||
}
|
||||
|
||||
private fun startFileUploadJobTag(user: User): String = JOB_FILES_UPLOAD + user.accountName
|
||||
private fun startFileUploadJobTag(accountName: String): String = JOB_FILES_UPLOAD + accountName
|
||||
|
||||
override fun isStartFileUploadJobScheduled(user: User): Boolean =
|
||||
workManager.isWorkScheduled(startFileUploadJobTag(user))
|
||||
override fun isStartFileUploadJobScheduled(accountName: String): Boolean =
|
||||
workManager.isWorkScheduled(startFileUploadJobTag(accountName))
|
||||
|
||||
/**
|
||||
* This method supports initiating uploads for various scenarios, including:
|
||||
@@ -656,7 +658,7 @@ internal class BackgroundJobManagerImpl(
|
||||
defaultDispatcherScope.launch {
|
||||
val batchSize = FileUploadHelper.MAX_FILE_COUNT
|
||||
val batches = uploadIds.toList().chunked(batchSize)
|
||||
val tag = startFileUploadJobTag(user)
|
||||
val tag = startFileUploadJobTag(user.accountName)
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
@@ -702,9 +704,6 @@ 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,
|
||||
@@ -824,4 +823,28 @@ 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,18 +1,27 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2019 Chris Narkiewicz <[email protected]>
|
||||
* 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.work.Worker
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.work.CoroutineWorker
|
||||
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.
|
||||
@@ -21,53 +30,113 @@ import com.owncloud.android.utils.FilesSyncHelper
|
||||
*
|
||||
* This job must not be started on API < 24.
|
||||
*/
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
class ContentObserverWork(
|
||||
appContext: Context,
|
||||
private val context: Context,
|
||||
private val params: WorkerParameters,
|
||||
private val syncedFolderProvider: SyncedFolderProvider,
|
||||
private val powerManagementService: PowerManagementService,
|
||||
private val backgroundJobManager: BackgroundJobManager
|
||||
) : Worker(appContext, params) {
|
||||
) : CoroutineWorker(context, params) {
|
||||
|
||||
override fun doWork(): Result {
|
||||
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
|
||||
|
||||
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
|
||||
companion object {
|
||||
private const val TAG = "🔍" + "ContentObserverWork"
|
||||
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_CONTENT_OBSERVER
|
||||
private const val NOTIFICATION_ID = 774
|
||||
}
|
||||
|
||||
private fun recheduleSelf() {
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
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.")
|
||||
backgroundJobManager.scheduleContentObserverJob()
|
||||
}
|
||||
|
||||
private fun checkAndStartFileSyncJob() {
|
||||
if (!powerManagementService.isPowerSavingEnabled && syncedFolderProvider.countEnabledSyncedFolders() > 0) {
|
||||
val changedFiles = mutableListOf<String>()
|
||||
for (uri in params.triggeredContentUris) {
|
||||
changedFiles.add(uri.toString())
|
||||
}
|
||||
FilesSyncHelper.startFilesSyncForAllFolders(
|
||||
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(
|
||||
syncedFolderProvider,
|
||||
backgroundJobManager,
|
||||
false,
|
||||
changedFiles.toTypedArray()
|
||||
contentUris
|
||||
)
|
||||
} else {
|
||||
Log_OC.w(TAG, "cant startFilesSyncForAllFolders")
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val TAG: String = ContentObserverWork::class.java.simpleName
|
||||
}
|
||||
}
|
||||
@@ -17,14 +17,16 @@ 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.NextcloudDatabase
|
||||
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.owncloud.android.MainApp
|
||||
import com.nextcloud.utils.extensions.updateStatus
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
@@ -43,7 +45,6 @@ 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 com.owncloud.android.utils.MimeTypeUtil
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
@@ -61,13 +62,14 @@ class AutoUploadWorker(
|
||||
private val connectivityService: ConnectivityService,
|
||||
private val powerManagementService: PowerManagementService,
|
||||
private val syncedFolderProvider: SyncedFolderProvider,
|
||||
private val backgroundJobManager: BackgroundJobManager
|
||||
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 CHANGED_FILES = "changedFiles"
|
||||
const val CONTENT_URIS = "content_uris"
|
||||
const val SYNCED_FOLDER_ID = "syncedFolderId"
|
||||
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD
|
||||
|
||||
@@ -83,24 +85,23 @@ class AutoUploadWorker(
|
||||
override suspend fun doWork(): Result {
|
||||
return try {
|
||||
val syncFolderId = inputData.getLong(SYNCED_FOLDER_ID, -1)
|
||||
val syncedFolder = syncedFolderProvider.getSyncedFolderByID(syncFolderId)
|
||||
if (syncedFolder == null || !syncedFolder.isEnabled) {
|
||||
Log_OC.e(TAG, "Skipping worker: syncedFolder $syncFolderId is not enabled!")
|
||||
return Result.failure()
|
||||
}
|
||||
this.syncedFolder = syncedFolder
|
||||
syncedFolder = syncedFolderProvider.getSyncedFolderByID(syncFolderId)
|
||||
?.takeIf { it.isEnabled } ?: return Result.failure()
|
||||
|
||||
// initial notification
|
||||
val notification = createNotification(context.getString(R.string.upload_files))
|
||||
updateForegroundInfo(notification)
|
||||
|
||||
val changedFiles = inputData.getStringArray(CHANGED_FILES)
|
||||
/**
|
||||
* Receives from [com.nextcloud.client.jobs.ContentObserverWork.checkAndTriggerAutoUpload]
|
||||
*/
|
||||
val contentUris = inputData.getStringArray(CONTENT_URIS)
|
||||
|
||||
if (canExitEarly(changedFiles, syncFolderId)) {
|
||||
if (canExitEarly(contentUris, syncFolderId)) {
|
||||
return Result.retry()
|
||||
}
|
||||
|
||||
collectFileChangesFromContentObserverWork(changedFiles)
|
||||
collectFileChangesFromContentObserverWork(contentUris)
|
||||
updateNotification()
|
||||
uploadFiles(syncedFolder)
|
||||
|
||||
@@ -146,11 +147,10 @@ class AutoUploadWorker(
|
||||
.build()
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
private fun getStartNotificationTitle(): Pair<String, String>? {
|
||||
private fun getStartNotificationTitle(): Pair<String, String>? = try {
|
||||
val localPath = syncedFolder.localPath
|
||||
val remotePath = syncedFolder.remotePath
|
||||
|
||||
return if (localPath.isBlank() || remotePath.isBlank()) {
|
||||
if (localPath.isBlank() || remotePath.isBlank()) {
|
||||
null
|
||||
} else {
|
||||
try {
|
||||
@@ -159,10 +159,12 @@ class AutoUploadWorker(
|
||||
null
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
private fun canExitEarly(changedFiles: Array<String>?, syncedFolderID: Long): Boolean {
|
||||
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")
|
||||
@@ -179,19 +181,16 @@ class AutoUploadWorker(
|
||||
return true
|
||||
}
|
||||
|
||||
val calculatedScanInterval =
|
||||
FilesSyncHelper.calculateScanInterval(syncedFolder, connectivityService, powerManagementService)
|
||||
val totalScanInterval = (syncedFolder.lastScanTimestampMs + calculatedScanInterval)
|
||||
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, "calculatedScanInterval: $calculatedScanInterval")
|
||||
Log_OC.d(TAG, "totalScanInterval: $totalScanInterval")
|
||||
Log_OC.d(TAG, "currentTime: $currentTime")
|
||||
Log_OC.d(TAG, "passedScanInterval: $passedScanInterval")
|
||||
|
||||
if (!passedScanInterval && changedFiles.isNullOrEmpty() && !overridePowerSaving) {
|
||||
if (!passedScanInterval && contentUris.isNullOrEmpty() && !overridePowerSaving) {
|
||||
Log_OC.w(
|
||||
TAG,
|
||||
"skipped since started before scan interval and nothing todo: " + syncedFolder.localPath
|
||||
@@ -202,61 +201,56 @@ class AutoUploadWorker(
|
||||
return false
|
||||
}
|
||||
|
||||
@Suppress("MagicNumber")
|
||||
private suspend fun collectFileChangesFromContentObserverWork(changedFiles: Array<String>?) =
|
||||
/**
|
||||
* 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 (changedFiles.isNullOrEmpty()) {
|
||||
// Check every file in synced folder for changes and update
|
||||
// filesystemDataProvider database (potentially needs a long time)
|
||||
if (contentUris.isNullOrEmpty()) {
|
||||
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
|
||||
} else {
|
||||
FilesSyncHelper.insertChangedEntries(syncedFolder, changedFiles)
|
||||
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]
|
||||
val dateFormat = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale)
|
||||
dateFormat.timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
|
||||
return dateFormat
|
||||
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, "uploadFilesFromFolder skipped user not present")
|
||||
Log_OC.w(TAG, "user not present")
|
||||
return null
|
||||
}
|
||||
return optionalUser.get()
|
||||
}
|
||||
|
||||
private fun buildPathsAndMimes(
|
||||
paths: Set<String>,
|
||||
syncedFolder: SyncedFolder,
|
||||
dateFormat: SimpleDateFormat
|
||||
): List<Triple<String, String, String>> {
|
||||
val lightVersion = context.resources.getBoolean(R.bool.syncedFolder_light)
|
||||
val currentLocale = context.resources.configuration.locales[0]
|
||||
|
||||
return paths.map { path ->
|
||||
val file = File(path)
|
||||
val localPath = file.absolutePath
|
||||
val remotePath =
|
||||
getRemotePath(file, syncedFolder, dateFormat, lightVersion, context.resources, currentLocale)
|
||||
val mimeType = MimeTypeUtil.getBestMimeTypeByFilename(localPath)
|
||||
Triple(localPath, remotePath, mimeType)
|
||||
}
|
||||
}
|
||||
|
||||
@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, "uploadFilesFromFolder light version is used")
|
||||
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(
|
||||
@@ -268,33 +262,113 @@ class AutoUploadWorker(
|
||||
Log_OC.d(TAG, "upload action is: $uploadAction")
|
||||
Triple(needsCharging, needsWifi, uploadAction)
|
||||
} else {
|
||||
Log_OC.d(TAG, "uploadFilesFromFolder not light version is used")
|
||||
Log_OC.d(TAG, "not light version is used")
|
||||
Triple(syncedFolder.isChargingOnly, syncedFolder.isWifiOnly, syncedFolder.uploadAction)
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("LongMethod", "DEPRECATION")
|
||||
@Suppress("LongMethod", "DEPRECATION", "TooGenericExceptionCaught")
|
||||
private suspend fun uploadFiles(syncedFolder: SyncedFolder) = withContext(Dispatchers.IO) {
|
||||
val dateFormat = prepareDateFormat()
|
||||
val user = getUserOrReturn(syncedFolder) ?: return@withContext
|
||||
val dao = NextcloudDatabase.Companion.getInstance(MainApp.getAppContext()).fileSystemDao()
|
||||
val repository = FileSystemRepository(dao)
|
||||
|
||||
val paths = repository.getAutoUploadFiles(syncedFolder)
|
||||
if (paths.isEmpty()) {
|
||||
Log_OC.w(TAG, "uploadFilesFromFolder skipped paths is empty")
|
||||
return@withContext
|
||||
}
|
||||
|
||||
val pathsAndMimes = buildPathsAndMimes(paths, syncedFolder, dateFormat)
|
||||
val (needsCharging, needsWifi, uploadAction) = getUploadSettings(syncedFolder)
|
||||
|
||||
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]
|
||||
|
||||
pathsAndMimes.forEach { (localPath, remotePath, _) ->
|
||||
val upload = OCUpload(localPath, remotePath, user.accountName).apply {
|
||||
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
|
||||
@@ -303,20 +377,10 @@ class AutoUploadWorker(
|
||||
isCreateRemoteFolder = true
|
||||
localAction = uploadAction
|
||||
}
|
||||
|
||||
uploadsStorageManager.storeUpload(upload)
|
||||
|
||||
val operation = createUploadFileOperation(upload, user)
|
||||
Log_OC.d(TAG, "🕒 uploading: $localPath")
|
||||
|
||||
val result = operation.execute(client)
|
||||
if (result.isSuccess) {
|
||||
repository.markFileAsUploaded(localPath, syncedFolder)
|
||||
Log_OC.d(TAG, "✅ auto upload completed: $localPath")
|
||||
} else {
|
||||
Log_OC.e(TAG, "❌ auto upload failed: $localPath")
|
||||
}
|
||||
uploadEntity = upload.toUploadEntity()
|
||||
}
|
||||
|
||||
return uploadEntity to upload
|
||||
}
|
||||
|
||||
private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation = UploadFileOperation(
|
||||
@@ -346,14 +410,12 @@ class AutoUploadWorker(
|
||||
val lastModificationTime = calculateLastModificationTime(file, syncedFolder, sFormatter)
|
||||
|
||||
val (remoteFolder, useSubfolders, subFolderRule) = if (lightVersion) {
|
||||
Log_OC.d(TAG, "getRemotePath light version is used")
|
||||
Triple(
|
||||
resources.getString(R.string.syncedFolder_remote_folder),
|
||||
resources.getBoolean(R.bool.syncedFolder_light_use_subfolders),
|
||||
SubFolderRule.YEAR_MONTH
|
||||
)
|
||||
} else {
|
||||
Log_OC.d(TAG, "getRemotePath not light version is used")
|
||||
Triple(
|
||||
syncedFolder.remotePath,
|
||||
syncedFolder.isSubfolderByDate,
|
||||
|
||||
@@ -15,28 +15,41 @@ import java.io.File
|
||||
|
||||
class FileSystemRepository(private val dao: FileSystemDao) {
|
||||
|
||||
suspend fun getAutoUploadFiles(syncedFolder: SyncedFolder): Set<String> {
|
||||
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 candidatePaths = dao.getAutoUploadFiles(syncedFolderId)
|
||||
val localPathsToUpload = mutableSetOf<String>()
|
||||
val entities = dao.getAutoUploadFilesEntities(syncedFolderId, BATCH_SIZE, lastId)
|
||||
val filtered = mutableListOf<Pair<String, Int>>()
|
||||
|
||||
candidatePaths.forEach { 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")
|
||||
localPathsToUpload.add(path)
|
||||
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 localPathsToUpload
|
||||
return filtered
|
||||
}
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
@@ -50,8 +63,4 @@ class FileSystemRepository(private val dao: FileSystemDao) {
|
||||
Log_OC.e(TAG, "Error marking file as uploaded: ${e.message}", e)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FilesystemRepository"
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,12 @@ 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
|
||||
@@ -29,6 +31,7 @@ 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 }
|
||||
@@ -44,17 +47,11 @@ class FileDownloadHelper {
|
||||
return false
|
||||
}
|
||||
|
||||
val fileStorageManager = FileDataStorageManager(user, MainApp.getAppContext().contentResolver)
|
||||
val topParentId = fileStorageManager.getTopParentId(file)
|
||||
|
||||
val isJobScheduled = backgroundJobManager.isStartFileDownloadJobScheduled(user, file.fileId)
|
||||
return isJobScheduled ||
|
||||
if (file.isFolder) {
|
||||
FileDownloadWorker.isDownloadingFolder(file.fileId) ||
|
||||
backgroundJobManager.isStartFileDownloadJobScheduled(user, topParentId)
|
||||
} else {
|
||||
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
|
||||
}
|
||||
return if (file.isFolder) {
|
||||
FolderDownloadWorker.isDownloading(file.fileId)
|
||||
} else {
|
||||
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelPendingOrCurrentDownloads(user: User?, files: List<OCFile>?) {
|
||||
@@ -141,4 +138,14 @@ 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()
|
||||
}
|
||||
@@ -24,7 +24,6 @@ import com.nextcloud.client.account.UserAccountManager
|
||||
import com.nextcloud.model.WorkerState
|
||||
import com.nextcloud.model.WorkerStateLiveData
|
||||
import com.nextcloud.utils.ForegroundServiceHelper
|
||||
import com.nextcloud.utils.extensions.getParentIdsOfSubfiles
|
||||
import com.nextcloud.utils.extensions.getPercent
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager
|
||||
@@ -45,7 +44,6 @@ import com.owncloud.android.utils.theme.ViewThemeUtils
|
||||
import java.util.AbstractList
|
||||
import java.util.Optional
|
||||
import java.util.Vector
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlin.random.Random
|
||||
|
||||
@Suppress("LongParameterList", "TooManyFunctions")
|
||||
@@ -63,7 +61,6 @@ class FileDownloadWorker(
|
||||
private val TAG = FileDownloadWorker::class.java.simpleName
|
||||
|
||||
private val pendingDownloads = IndexedForest<DownloadFileOperation>()
|
||||
private val pendingFolderDownloads: MutableSet<Long> = ConcurrentHashMap.newKeySet<Long>()
|
||||
|
||||
fun cancelOperation(accountName: String, fileId: Long) {
|
||||
pendingDownloads.all.forEach {
|
||||
@@ -75,8 +72,6 @@ class FileDownloadWorker(
|
||||
it.value?.payload?.isMatching(accountName, fileId) == true
|
||||
}
|
||||
|
||||
fun isDownloadingFolder(id: Long): Boolean = pendingFolderDownloads.contains(id)
|
||||
|
||||
const val FILE_REMOTE_PATH = "FILE_REMOTE_PATH"
|
||||
const val ACCOUNT_NAME = "ACCOUNT_NAME"
|
||||
const val BEHAVIOUR = "BEHAVIOUR"
|
||||
@@ -170,10 +165,6 @@ class FileDownloadWorker(
|
||||
|
||||
private fun getRequestDownloads(ocFile: OCFile): AbstractList<String> {
|
||||
val files = getFiles(ocFile)
|
||||
val filesPaths = files.map { it.remotePath }
|
||||
val parentIdsOfSubFiles = fileDataStorageManager?.getParentIdsOfSubfiles(filesPaths) ?: listOf()
|
||||
pendingFolderDownloads.addAll(parentIdsOfSubFiles)
|
||||
|
||||
val downloadType = getDownloadType()
|
||||
|
||||
conflictUploadId = inputData.keyValueMap[CONFLICT_UPLOAD_ID] as Long?
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* 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
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* 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)
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* 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()
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,14 @@
|
||||
*/
|
||||
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
|
||||
@@ -20,6 +23,7 @@ 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
|
||||
@@ -35,13 +39,12 @@ 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
|
||||
|
||||
@@ -205,7 +208,7 @@ class FileUploadHelper {
|
||||
showSameFileAlreadyExistsNotification: Boolean = true
|
||||
) {
|
||||
val uploads = localPaths.mapIndexed { index, localPath ->
|
||||
OCUpload(localPath, remotePaths[index], user.accountName).apply {
|
||||
val result = OCUpload(localPath, remotePaths[index], user.accountName).apply {
|
||||
this.nameCollisionPolicy = nameCollisionPolicy
|
||||
isUseWifiOnly = requiresWifi
|
||||
isWhileChargingOnly = requiresCharging
|
||||
@@ -214,47 +217,30 @@ class FileUploadHelper {
|
||||
isCreateRemoteFolder = createRemoteFolder
|
||||
localAction = localBehavior
|
||||
}
|
||||
|
||||
val id = uploadsStorageManager.uploadDao.insertOrReplace(result.toUploadEntity())
|
||||
result.uploadId = id
|
||||
result
|
||||
}
|
||||
uploadsStorageManager.storeUploads(uploads)
|
||||
backgroundJobManager.startFilesUploadJob(user, uploads.getUploadIds(), showSameFileAlreadyExistsNotification)
|
||||
}
|
||||
|
||||
fun removeFileUpload(remotePath: String, accountName: String) {
|
||||
try {
|
||||
val user = accountManager.getUser(accountName).get()
|
||||
|
||||
// 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)
|
||||
}
|
||||
uploadsStorageManager.uploadDao.deleteByAccountAndRemotePath(accountName, remotePath)
|
||||
}
|
||||
|
||||
fun cancelFileUpload(remotePath: String, accountName: String) {
|
||||
fun updateUploadStatus(remotePath: String, accountName: String, status: UploadStatus) {
|
||||
ioScope.launch {
|
||||
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!")
|
||||
}
|
||||
uploadsStorageManager.uploadDao.updateStatus(remotePath, accountName, status.value)
|
||||
}
|
||||
}
|
||||
|
||||
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 getUploadsByStatus(accountName: String, status: UploadStatus, onCompleted: (Array<OCUpload>) -> Unit) {
|
||||
ioScope.launch {
|
||||
val result =
|
||||
uploadsStorageManager.uploadDao.getUploadsByStatus(accountName, status.value)
|
||||
.map { it.toOCUpload(null) }.toTypedArray()
|
||||
onCompleted(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,26 +252,16 @@ class FileUploadHelper {
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
fun isUploading(user: User?, file: OCFile?): Boolean {
|
||||
if (user == null || file == null || !backgroundJobManager.isStartFileUploadJobScheduled(user)) {
|
||||
fun isUploading(remotePath: String?, accountName: String?): Boolean {
|
||||
accountName ?: return false
|
||||
if (!backgroundJobManager.isStartFileUploadJobScheduled(accountName)) {
|
||||
return false
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
remotePath ?: return false
|
||||
val upload = uploadsStorageManager.uploadDao.getByRemotePath(remotePath)
|
||||
return upload?.status == UploadStatus.UPLOAD_IN_PROGRESS.value ||
|
||||
FileUploadWorker.isUploading(remotePath, accountName)
|
||||
}
|
||||
|
||||
private fun checkConnectivity(connectivityService: ConnectivityService): Boolean {
|
||||
@@ -364,7 +340,7 @@ class FileUploadHelper {
|
||||
|
||||
val uploads = existingFiles.map { file ->
|
||||
file?.let {
|
||||
OCUpload(file, user).apply {
|
||||
val result = OCUpload(file, user).apply {
|
||||
fileSize = file.fileLength
|
||||
this.nameCollisionPolicy = nameCollisionPolicy
|
||||
isCreateRemoteFolder = true
|
||||
@@ -373,9 +349,12 @@ 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)
|
||||
}
|
||||
@@ -459,6 +438,14 @@ 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)
|
||||
@@ -474,7 +461,9 @@ class FileUploadHelper {
|
||||
return
|
||||
}
|
||||
|
||||
instance().cancelFileUpload(remotePath, accountName)
|
||||
FileUploadWorker.cancelCurrentUpload(remotePath, accountName, onCompleted = {
|
||||
instance().updateUploadStatus(remotePath, accountName, UploadStatus.UPLOAD_CANCELLED)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
*/
|
||||
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.Worker
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.nextcloud.client.account.User
|
||||
import com.nextcloud.client.account.UserAccountManager
|
||||
@@ -21,8 +23,12 @@ 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
|
||||
@@ -34,8 +40,12 @@ 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
|
||||
|
||||
@@ -51,7 +61,7 @@ class FileUploadWorker(
|
||||
val preferences: AppPreferences,
|
||||
val context: Context,
|
||||
params: WorkerParameters
|
||||
) : Worker(context, params),
|
||||
) : CoroutineWorker(context, params),
|
||||
OnDatatransferProgressListener {
|
||||
|
||||
companion object {
|
||||
@@ -91,19 +101,44 @@ 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 notificationManager = UploadNotificationManager(context, viewThemeUtils, Random.nextInt())
|
||||
private val notificationId = Random.nextInt()
|
||||
private val notificationManager = UploadNotificationManager(context, viewThemeUtils, notificationId)
|
||||
private val intents = FileUploaderIntents(context)
|
||||
private val fileUploaderDelegate = FileUploaderDelegate()
|
||||
|
||||
@Suppress("TooGenericExceptionCaught")
|
||||
override fun doWork(): Result = try {
|
||||
override suspend fun doWork(): Result = try {
|
||||
Log_OC.d(TAG, "FileUploadWorker started")
|
||||
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
|
||||
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)
|
||||
|
||||
val result = uploadFiles()
|
||||
backgroundJobManager.logEndOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class), result)
|
||||
backgroundJobManager.logEndOfWorker(workerName, result)
|
||||
notificationManager.dismissNotification()
|
||||
if (result == Result.success()) {
|
||||
setIdleWorkerState()
|
||||
@@ -111,17 +146,37 @@ class FileUploadWorker(
|
||||
result
|
||||
} catch (t: Throwable) {
|
||||
Log_OC.e(TAG, "Error caught at FileUploadWorker $t")
|
||||
cleanup()
|
||||
Result.failure()
|
||||
}
|
||||
|
||||
override fun onStopped() {
|
||||
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() {
|
||||
Log_OC.e(TAG, "FileUploadWorker stopped")
|
||||
|
||||
setIdleWorkerState()
|
||||
currentUploadFileOperation?.cancel(null)
|
||||
notificationManager.dismissNotification()
|
||||
|
||||
super.onStopped()
|
||||
}
|
||||
|
||||
private fun setWorkerState(user: User?) {
|
||||
@@ -133,36 +188,36 @@ class FileUploadWorker(
|
||||
}
|
||||
|
||||
@Suppress("ReturnCount", "LongMethod")
|
||||
private fun uploadFiles(): Result {
|
||||
private suspend fun uploadFiles(): Result = withContext(Dispatchers.IO) {
|
||||
val accountName = inputData.getString(ACCOUNT)
|
||||
if (accountName == null) {
|
||||
Log_OC.e(TAG, "accountName is null")
|
||||
return Result.failure()
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
val uploadIds = inputData.getLongArray(UPLOAD_IDS)
|
||||
if (uploadIds == null) {
|
||||
Log_OC.e(TAG, "uploadIds is null")
|
||||
return Result.failure()
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
val currentBatchIndex = inputData.getInt(CURRENT_BATCH_INDEX, -1)
|
||||
if (currentBatchIndex == -1) {
|
||||
Log_OC.e(TAG, "currentBatchIndex is -1, cancelling")
|
||||
return Result.failure()
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
val totalUploadSize = inputData.getInt(TOTAL_UPLOAD_SIZE, -1)
|
||||
if (totalUploadSize == -1) {
|
||||
Log_OC.e(TAG, "totalUploadSize is -1, cancelling")
|
||||
return Result.failure()
|
||||
return@withContext 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 Result.failure()
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
val user = optionalUser.get()
|
||||
@@ -172,21 +227,19 @@ class FileUploadWorker(
|
||||
val client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context)
|
||||
|
||||
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 Result.success()
|
||||
return@withContext Result.success()
|
||||
}
|
||||
|
||||
if (canExitEarly()) {
|
||||
notificationManager.showConnectionErrorNotification()
|
||||
return Result.failure()
|
||||
}
|
||||
|
||||
if (isStopped) {
|
||||
continue
|
||||
return@withContext Result.failure()
|
||||
}
|
||||
|
||||
setWorkerState(user)
|
||||
@@ -203,12 +256,16 @@ class FileUploadWorker(
|
||||
totalUploadSize = totalUploadSize
|
||||
)
|
||||
|
||||
val result = upload(operation, user, client)
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
upload(operation, user, client)
|
||||
}
|
||||
val entity = uploadsStorageManager.uploadDao.getUploadById(upload.uploadId, accountName)
|
||||
uploadsStorageManager.updateStatus(entity, result.isSuccess)
|
||||
currentUploadFileOperation = null
|
||||
sendUploadFinishEvent(totalUploadSize, currentUploadIndex, operation, result)
|
||||
}
|
||||
|
||||
return Result.success()
|
||||
return@withContext Result.success()
|
||||
}
|
||||
|
||||
private fun sendUploadFinishEvent(
|
||||
@@ -346,6 +403,10 @@ class FileUploadWorker(
|
||||
return
|
||||
}
|
||||
|
||||
if (uploadResult.code == ResultCode.USER_CANCELLED) {
|
||||
return
|
||||
}
|
||||
|
||||
notificationManager.run {
|
||||
val errorMessage = ErrorMessageAdapter.getErrorCauseMessage(
|
||||
uploadResult,
|
||||
|
||||
@@ -132,6 +132,7 @@ class WhatsNewActivity :
|
||||
object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
onFinish()
|
||||
isEnabled = false
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,12 @@ 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);
|
||||
|
||||
@@ -70,6 +70,8 @@ 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";
|
||||
@@ -228,6 +230,26 @@ 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);
|
||||
|
||||
@@ -84,6 +84,7 @@ class ChooseAccountDialogFragment :
|
||||
return builder.create()
|
||||
}
|
||||
|
||||
@Suppress("LongMethod")
|
||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||||
super.onViewCreated(view, savedInstanceState)
|
||||
accountManager = (activity as BaseActivity).userAccountManager
|
||||
|
||||
@@ -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),
|
||||
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),
|
||||
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),
|
||||
|
||||
// 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,
|
||||
SYNC_FILE,
|
||||
DOWNLOAD_FOLDER,
|
||||
CANCEL_SYNC,
|
||||
SELECT_ALL,
|
||||
SELECT_NONE,
|
||||
|
||||
@@ -8,7 +8,10 @@
|
||||
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)
|
||||
@@ -38,3 +41,79 @@ 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,52 +45,62 @@ class ShortcutUtil @Inject constructor(private val mContext: Context) {
|
||||
user: User,
|
||||
syncedFolderProvider: SyncedFolderProvider
|
||||
) {
|
||||
if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
|
||||
val intent = Intent(mContext, FileDisplayActivity::class.java)
|
||||
intent.action = FileDisplayActivity.OPEN_FILE
|
||||
intent.putExtra(FileActivity.EXTRA_FILE, file.remotePath)
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
val shortcutId = "nextcloud_shortcut_" + file.remoteId
|
||||
val icon: IconCompat
|
||||
var thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
|
||||
ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.remoteId
|
||||
)
|
||||
if (thumbnail != null) {
|
||||
thumbnail = bitmapToAdaptiveBitmap(thumbnail)
|
||||
icon = IconCompat.createWithAdaptiveBitmap(thumbnail)
|
||||
} else if (file.isFolder) {
|
||||
if (!ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
|
||||
return
|
||||
}
|
||||
|
||||
val intent = Intent(mContext, FileDisplayActivity::class.java).apply {
|
||||
action = FileDisplayActivity.OPEN_FILE
|
||||
putExtra(FileActivity.EXTRA_FILE_REMOTE_PATH, file.decryptedRemotePath)
|
||||
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
}
|
||||
|
||||
val icon = createShortcutIcon(file, viewThemeUtils, user, syncedFolderProvider)
|
||||
|
||||
val shortcutInfo = ShortcutInfoCompat.Builder(mContext, "nextcloud_shortcut_${file.remoteId}")
|
||||
.setShortLabel(file.fileName)
|
||||
.setLongLabel(mContext.getString(R.string.pin_shortcut_label, file.fileName))
|
||||
.setIcon(icon)
|
||||
.setIntent(intent)
|
||||
.build()
|
||||
|
||||
val resultIntent =
|
||||
ShortcutManagerCompat.createShortcutResultIntent(mContext, shortcutInfo)
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
mContext,
|
||||
file.hashCode(),
|
||||
resultIntent,
|
||||
FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
ShortcutManagerCompat.requestPinShortcut(mContext, shortcutInfo, pendingIntent.intentSender)
|
||||
}
|
||||
|
||||
private fun createShortcutIcon(
|
||||
file: OCFile,
|
||||
viewThemeUtils: ViewThemeUtils,
|
||||
user: User,
|
||||
syncedFolderProvider: SyncedFolderProvider
|
||||
): IconCompat {
|
||||
val thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(
|
||||
ThumbnailsCacheManager.PREFIX_THUMBNAIL + file.remoteId
|
||||
)
|
||||
|
||||
return when {
|
||||
thumbnail != null -> IconCompat.createWithAdaptiveBitmap(bitmapToAdaptiveBitmap(thumbnail))
|
||||
|
||||
file.isFolder -> {
|
||||
val isAutoUploadFolder = SyncedFolderProvider.isAutoUploadFolder(syncedFolderProvider, file, user)
|
||||
val isDarkModeActive = syncedFolderProvider.preferences.isDarkModeEnabled
|
||||
|
||||
val overlayIconId = file.getFileOverlayIconId(isAutoUploadFolder)
|
||||
val drawable = MimeTypeUtil.getFolderIcon(isDarkModeActive, overlayIconId, mContext, viewThemeUtils)
|
||||
val bitmapIcon = drawable.toBitmap()
|
||||
icon = IconCompat.createWithBitmap(bitmapIcon)
|
||||
} else {
|
||||
icon = IconCompat.createWithResource(
|
||||
mContext,
|
||||
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
|
||||
)
|
||||
IconCompat.createWithBitmap(drawable.toBitmap())
|
||||
}
|
||||
val longLabel = mContext.getString(R.string.pin_shortcut_label, file.fileName)
|
||||
val pinShortcutInfo = ShortcutInfoCompat.Builder(mContext, shortcutId)
|
||||
.setShortLabel(file.fileName)
|
||||
.setLongLabel(longLabel)
|
||||
.setIcon(icon)
|
||||
.setIntent(intent)
|
||||
.build()
|
||||
val pinnedShortcutCallbackIntent =
|
||||
ShortcutManagerCompat.createShortcutResultIntent(mContext, pinShortcutInfo)
|
||||
val successCallback = PendingIntent.getBroadcast(
|
||||
|
||||
else -> IconCompat.createWithResource(
|
||||
mContext,
|
||||
0,
|
||||
pinnedShortcutCallbackIntent,
|
||||
FLAG_IMMUTABLE
|
||||
)
|
||||
ShortcutManagerCompat.requestPinShortcut(
|
||||
mContext,
|
||||
pinShortcutInfo,
|
||||
successCallback.intentSender
|
||||
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
@@ -10,22 +10,10 @@ package com.nextcloud.utils.extensions
|
||||
import android.content.Intent
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.ui.activity.DrawerActivity
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
|
||||
@Suppress("ReturnCount")
|
||||
fun DrawerActivity.handleBackButtonEvent(currentDir: OCFile): Boolean {
|
||||
if (DrawerActivity.menuItemId == R.id.nav_all_files && currentDir.isRootDirectory) {
|
||||
moveTaskToBack(true)
|
||||
return true
|
||||
}
|
||||
|
||||
val isParentDirExists = (storageManager.getFileById(currentDir.parentId) != null)
|
||||
if (isParentDirExists) {
|
||||
return false
|
||||
}
|
||||
|
||||
fun DrawerActivity.navigateToAllFiles() {
|
||||
DrawerActivity.menuItemId = R.id.nav_all_files
|
||||
setNavigationViewItemChecked()
|
||||
|
||||
@@ -38,6 +26,4 @@ fun DrawerActivity.handleBackButtonEvent(currentDir: OCFile): Boolean {
|
||||
}.run {
|
||||
startActivity(this)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -15,9 +15,6 @@ fun FileDataStorageManager.searchFilesByName(file: OCFile, accountName: String,
|
||||
createFileInstance(it)
|
||||
}
|
||||
|
||||
fun FileDataStorageManager.getParentIdsOfSubfiles(paths: List<String>): List<Long> =
|
||||
fileDao.getParentIdsOfSubfiles(paths)
|
||||
|
||||
fun FileDataStorageManager.getDecryptedPath(file: OCFile): String {
|
||||
val paths = mutableListOf<String>()
|
||||
var entity = fileDao.getFileByEncryptedRemotePath(file.remotePath, user.accountName)
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.jobs.BackgroundJobManagerImpl
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.datamodel.SyncedFolder
|
||||
import com.owncloud.android.datamodel.SyncedFolderDisplayItem
|
||||
import java.io.File
|
||||
@@ -25,3 +29,27 @@ fun List<SyncedFolder>.hasEnabledParent(localPath: String?): Boolean {
|
||||
return any { it.isEnabled && File(it.localPath).exists() && File(it.localPath) == parent } ||
|
||||
hasEnabledParent(parent.absolutePath)
|
||||
}
|
||||
|
||||
@Suppress("MagicNumber", "ReturnCount")
|
||||
fun SyncedFolder.calculateScanInterval(
|
||||
connectivityService: ConnectivityService,
|
||||
powerManagementService: PowerManagementService
|
||||
): Pair<Long, Int?> {
|
||||
val defaultIntervalMillis = BackgroundJobManagerImpl.DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES * 60_000L
|
||||
|
||||
if (!connectivityService.isConnected() || connectivityService.isInternetWalled()) {
|
||||
return defaultIntervalMillis * 2 to null
|
||||
}
|
||||
|
||||
if (isWifiOnly && !connectivityService.getConnectivity().isWifi) {
|
||||
return defaultIntervalMillis * 4 to R.string.auto_upload_wifi_only_warning_info
|
||||
}
|
||||
|
||||
val batteryLevel = powerManagementService.battery.level
|
||||
return when {
|
||||
batteryLevel < 20 -> defaultIntervalMillis * 8 to R.string.auto_upload_low_battery_warning_info
|
||||
batteryLevel < 50 -> defaultIntervalMillis * 4 to R.string.auto_upload_low_battery_warning_info
|
||||
batteryLevel < 80 -> defaultIntervalMillis * 2 to null
|
||||
else -> defaultIntervalMillis to null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import android.provider.MediaStore
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import androidx.core.net.toUri
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
/**
|
||||
* Retrieves the orientation of an image file from its EXIF metadata or, as a fallback,
|
||||
* from the Android MediaStore.
|
||||
*
|
||||
* This function first attempts to read the orientation using [ExifInterface.TAG_ORIENTATION]
|
||||
* directly from the file at the given [path]. If that fails or returns
|
||||
* [ExifInterface.ORIENTATION_UNDEFINED], it then queries the MediaStore for the image's
|
||||
* stored orientation in degrees (0, 90, 180, or 270), converting that to an EXIF-compatible
|
||||
* orientation constant.
|
||||
*
|
||||
* @param path Absolute file path or content URI (as string) of the image.
|
||||
* @return One of the [ExifInterface] orientation constants, e.g.
|
||||
* [ExifInterface.ORIENTATION_ROTATE_90], or [ExifInterface.ORIENTATION_UNDEFINED]
|
||||
* if the orientation could not be determined.
|
||||
*
|
||||
* @see ExifInterface
|
||||
* @see MediaStore.Images.Media.ORIENTATION
|
||||
*/
|
||||
@Suppress("TooGenericExceptionCaught", "NestedBlockDepth", "MagicNumber")
|
||||
fun getExifOrientation(path: String): Int {
|
||||
val context = MainApp.getAppContext()
|
||||
if (context == null || path.isBlank()) {
|
||||
return ExifInterface.ORIENTATION_UNDEFINED
|
||||
}
|
||||
|
||||
var orientation = ExifInterface.ORIENTATION_UNDEFINED
|
||||
|
||||
try {
|
||||
val exif = ExifInterface(path)
|
||||
orientation = exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_UNDEFINED
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e("ThumbnailsCacheManager", "getExifOrientation exception: $e")
|
||||
}
|
||||
|
||||
// Fallback: query MediaStore if EXIF is undefined
|
||||
if (orientation == ExifInterface.ORIENTATION_UNDEFINED) {
|
||||
try {
|
||||
val uri = path.toUri()
|
||||
val projection = arrayOf(MediaStore.Images.Media.ORIENTATION)
|
||||
|
||||
context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
|
||||
if (cursor.moveToFirst()) {
|
||||
val orientationIndex = cursor.getColumnIndexOrThrow(projection[0])
|
||||
val degrees = cursor.getInt(orientationIndex)
|
||||
orientation = when (degrees) {
|
||||
90 -> ExifInterface.ORIENTATION_ROTATE_90
|
||||
180 -> ExifInterface.ORIENTATION_ROTATE_180
|
||||
270 -> ExifInterface.ORIENTATION_ROTATE_270
|
||||
else -> ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e("ThumbnailsCacheManager", "getExifOrientation exception: $e")
|
||||
}
|
||||
}
|
||||
|
||||
return orientation
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import com.nextcloud.client.database.entity.UploadEntity
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager
|
||||
|
||||
fun UploadsStorageManager.updateStatus(entity: UploadEntity?, status: UploadsStorageManager.UploadStatus) {
|
||||
entity ?: return
|
||||
uploadDao.insertOrReplace(entity.withStatus(status))
|
||||
}
|
||||
|
||||
fun UploadsStorageManager.updateStatus(entity: UploadEntity?, success: Boolean) {
|
||||
entity ?: return
|
||||
val newStatus = if (success) {
|
||||
UploadsStorageManager.UploadStatus.UPLOAD_SUCCEEDED
|
||||
} else {
|
||||
UploadsStorageManager.UploadStatus.UPLOAD_FAILED
|
||||
}
|
||||
uploadDao.insertOrReplace(entity.withStatus(newStatus))
|
||||
}
|
||||
|
||||
private fun UploadEntity.withStatus(newStatus: UploadsStorageManager.UploadStatus) = this.copy(status = newStatus.value)
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
package com.nextcloud.utils.extensions
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.MediaStore
|
||||
import com.owncloud.android.lib.common.utils.Log_OC
|
||||
|
||||
/**
|
||||
* Returns absolute filesystem path to the media item on disk. I/O errors that could occur. From Android 11 onwards,
|
||||
* this column is read-only for apps that target R and higher.
|
||||
*
|
||||
* [More Info](https://developer.android.com/reference/android/provider/MediaStore.MediaColumns#DATA)
|
||||
*/
|
||||
@Suppress("ReturnCount", "TooGenericExceptionCaught")
|
||||
fun Uri.toFilePath(context: Context): String? {
|
||||
try {
|
||||
val projection = arrayOf(MediaStore.MediaColumns.DATA)
|
||||
|
||||
val resolver = context.contentResolver
|
||||
|
||||
resolver.query(this, projection, null, null, null)?.use { cursor ->
|
||||
if (!cursor.moveToFirst()) {
|
||||
return null
|
||||
}
|
||||
|
||||
val dataIdx = cursor.getColumnIndex(MediaStore.MediaColumns.DATA)
|
||||
val data = if (dataIdx != -1) cursor.getString(dataIdx) else null
|
||||
return data
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (e: Exception) {
|
||||
Log_OC.e("UriExtensions", "exception, toFilePath: $e")
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -636,7 +636,7 @@ public class MainApp extends Application implements HasAndroidInjector, NetworkC
|
||||
}
|
||||
|
||||
if (!preferences.isAutoUploadInitialized()) {
|
||||
FilesSyncHelper.startFilesSyncForAllFolders(syncedFolderProvider, backgroundJobManager,false, new String[]{});
|
||||
FilesSyncHelper.startAutoUploadImmediately(syncedFolderProvider, backgroundJobManager, false);
|
||||
preferences.setAutoUploadInit(true);
|
||||
}
|
||||
|
||||
@@ -706,6 +706,13 @@ public class MainApp extends Application implements HasAndroidInjector, NetworkC
|
||||
createChannel(notificationManager, NotificationUtils.NOTIFICATION_CHANNEL_OFFLINE_OPERATIONS,
|
||||
R.string.notification_channel_offline_operations_name_short,
|
||||
R.string.notification_channel_offline_operations_description, context);
|
||||
|
||||
createChannel(notificationManager,
|
||||
NotificationUtils.NOTIFICATION_CHANNEL_CONTENT_OBSERVER,
|
||||
R.string.notification_channel_content_observer_name_short,
|
||||
R.string.notification_channel_content_observer_description,
|
||||
context,
|
||||
NotificationManager.IMPORTANCE_LOW);
|
||||
} else {
|
||||
Log_OC.e(TAG, "Notification manager is null");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,10 @@
|
||||
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import com.nextcloud.client.device.PowerManagementService;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.client.preferences.SubFolderRule;
|
||||
import com.nextcloud.utils.extensions.SyncedFolderExtensionsKt;
|
||||
import com.owncloud.android.files.services.NameCollisionPolicy;
|
||||
import com.owncloud.android.utils.MimeTypeUtil;
|
||||
|
||||
@@ -105,7 +108,7 @@ public class SyncedFolder implements Serializable, Cloneable {
|
||||
*
|
||||
* @param id id
|
||||
*/
|
||||
protected SyncedFolder(long id,
|
||||
public SyncedFolder(long id,
|
||||
String localPath,
|
||||
String remotePath,
|
||||
boolean wifiOnly,
|
||||
@@ -276,15 +279,20 @@ public class SyncedFolder implements Serializable, Cloneable {
|
||||
this.excludeHidden = excludeHidden;
|
||||
}
|
||||
|
||||
public boolean containsTypedFile(String filePath){
|
||||
public boolean containsTypedFile(File file,String filePath){
|
||||
boolean isCorrectMediaType =
|
||||
(getType() == MediaFolderType.IMAGE && MimeTypeUtil.isImage(new File(filePath))) ||
|
||||
(getType() == MediaFolderType.VIDEO && MimeTypeUtil.isVideo(new File(filePath))) ||
|
||||
getType() == MediaFolderType.CUSTOM;
|
||||
(getType() == MediaFolderType.IMAGE && MimeTypeUtil.isImage(file)) ||
|
||||
(getType() == MediaFolderType.VIDEO && MimeTypeUtil.isVideo(file)) ||
|
||||
getType() == MediaFolderType.CUSTOM;
|
||||
return filePath.contains(localPath) && isCorrectMediaType;
|
||||
}
|
||||
|
||||
public long getLastScanTimestampMs() { return lastScanTimestampMs; }
|
||||
|
||||
public void setLastScanTimestampMs(long lastScanTimestampMs) { this.lastScanTimestampMs = lastScanTimestampMs; }
|
||||
|
||||
public long getTotalScanInterval(ConnectivityService connectivityService, PowerManagementService powerManagementService) {
|
||||
final var calculatedScanInterval = SyncedFolderExtensionsKt.calculateScanInterval(this, connectivityService, powerManagementService);
|
||||
return lastScanTimestampMs + calculatedScanInterval.getFirst();
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,14 @@ import android.net.Uri;
|
||||
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.core.Clock;
|
||||
import com.nextcloud.client.database.NextcloudDatabase;
|
||||
import com.nextcloud.client.database.dao.SyncedFolderDao;
|
||||
import com.nextcloud.client.database.entity.SyncedFolderEntity;
|
||||
import com.nextcloud.client.database.entity.SyncedFolderEntityKt;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl;
|
||||
import com.nextcloud.client.preferences.SubFolderRule;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.db.ProviderMeta;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.lib.resources.files.model.ServerFileInterface;
|
||||
@@ -42,6 +47,7 @@ public class SyncedFolderProvider extends Observable {
|
||||
private final ContentResolver mContentResolver;
|
||||
private final AppPreferences preferences;
|
||||
private final Clock clock;
|
||||
public final SyncedFolderDao dao = NextcloudDatabase.getInstance(MainApp.getAppContext()).syncedFolderDao();
|
||||
|
||||
/**
|
||||
* constructor.
|
||||
@@ -183,33 +189,11 @@ public class SyncedFolderProvider extends Observable {
|
||||
}
|
||||
|
||||
public SyncedFolder findByLocalPathAndAccount(String localPath, User user) {
|
||||
SyncedFolder result = null;
|
||||
Cursor cursor = mContentResolver.query(
|
||||
ProviderMeta.ProviderTableMeta.CONTENT_URI_SYNCED_FOLDERS,
|
||||
null,
|
||||
ProviderMeta.ProviderTableMeta.SYNCED_FOLDER_LOCAL_PATH + " LIKE ? AND " +
|
||||
ProviderMeta.ProviderTableMeta.SYNCED_FOLDER_ACCOUNT + " =? ",
|
||||
new String[]{localPath + "%", user.getAccountName()},
|
||||
null
|
||||
);
|
||||
|
||||
if (cursor != null && cursor.getCount() == 1) {
|
||||
result = createSyncedFolderFromCursor(cursor);
|
||||
} else {
|
||||
if (cursor == null) {
|
||||
Log_OC.e(TAG, "Sync folder db cursor for local path=" + localPath + " in NULL.");
|
||||
} else {
|
||||
Log_OC.e(TAG, cursor.getCount() + " items for local path=" + localPath
|
||||
+ " available in sync folder db. Expected 1. Failed to update sync folder db.");
|
||||
}
|
||||
final SyncedFolderEntity entity = dao.findByLocalPathAndAccount(localPath, user.getAccountName());
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (cursor != null) {
|
||||
cursor.close();
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
return SyncedFolderEntityKt.toSyncedFolder(entity);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
|
||||
@@ -37,6 +37,7 @@ import android.widget.ImageView;
|
||||
import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.utils.BitmapExtensionsKt;
|
||||
import com.nextcloud.utils.extensions.ThumbnailsCacheManagerExtensionsKt;
|
||||
import com.owncloud.android.MainApp;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.lib.common.OwnCloudAccount;
|
||||
@@ -77,6 +78,8 @@ import androidx.core.content.ContextCompat;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
|
||||
|
||||
import static com.nextcloud.utils.extensions.ThumbnailsCacheManagerExtensionsKt.getExifOrientation;
|
||||
|
||||
/**
|
||||
* Manager for concurrent access to thumbnails cache.
|
||||
*/
|
||||
@@ -194,7 +197,8 @@ public final class ThumbnailsCacheManager {
|
||||
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
|
||||
|
||||
// Rotate image, obeying exif tag
|
||||
thumbnail = BitmapUtils.rotateImage(thumbnail,path);
|
||||
int orientation = getExifOrientation(path);
|
||||
thumbnail = BitmapExtensionsKt.rotateBitmapViaExif(thumbnail, orientation);
|
||||
|
||||
// Add thumbnail to cache
|
||||
// do not overwrite any pre-existing image
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/*
|
||||
* Nextcloud - Android Client
|
||||
*
|
||||
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2024 Jonas Mayer <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2022 Álvaro Brey <[email protected]>
|
||||
* SPDX-FileCopyrightText: 2018-2020 Tobias Kaminsky <[email protected]>
|
||||
@@ -14,14 +15,9 @@
|
||||
*/
|
||||
package com.owncloud.android.datamodel;
|
||||
|
||||
import android.content.ContentProviderOperation;
|
||||
import android.content.ContentProviderResult;
|
||||
import android.content.ContentResolver;
|
||||
import android.content.ContentValues;
|
||||
import android.content.OperationApplicationException;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.RemoteException;
|
||||
|
||||
import com.nextcloud.client.account.CurrentAccountProvider;
|
||||
import com.nextcloud.client.account.User;
|
||||
@@ -94,97 +90,6 @@ public class UploadsStorageManager extends Observable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores an upload object in DB.
|
||||
*
|
||||
* @param ocUpload Upload object to store
|
||||
* @return upload id, -1 if the insert process fails.
|
||||
*/
|
||||
public long storeUpload(OCUpload ocUpload) {
|
||||
OCUpload existingUpload = getPendingCurrentOrFailedUpload(ocUpload);
|
||||
if (existingUpload != null) {
|
||||
Log_OC.v(TAG, "Will update upload in db since " + ocUpload.getLocalPath() + " already exists as " +
|
||||
"pending, current or failed upload");
|
||||
long existingId = existingUpload.getUploadId();
|
||||
ocUpload.setUploadId(existingId);
|
||||
updateUpload(ocUpload);
|
||||
return existingId;
|
||||
}
|
||||
|
||||
|
||||
Log_OC.v(TAG, "Inserting " + ocUpload.getLocalPath() + " with status=" + ocUpload.getUploadStatus());
|
||||
|
||||
ContentValues cv = getContentValues(ocUpload);
|
||||
Uri result = getDB().insert(ProviderTableMeta.CONTENT_URI_UPLOADS, cv);
|
||||
|
||||
Log_OC.d(TAG, "storeUpload returns with: " + result + " for file: " + ocUpload.getLocalPath());
|
||||
if (result == null) {
|
||||
Log_OC.e(TAG, "Failed to insert item " + ocUpload.getLocalPath() + " into upload db.");
|
||||
return -1;
|
||||
} else {
|
||||
long new_id = Long.parseLong(result.getPathSegments().get(1));
|
||||
ocUpload.setUploadId(new_id);
|
||||
notifyObserversNow();
|
||||
|
||||
return new_id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void storeUploads(final List<OCUpload> ocUploads) {
|
||||
Log_OC.v(TAG, "Inserting " + ocUploads.size() + " uploads");
|
||||
ArrayList<ContentProviderOperation> operations = new ArrayList<>(ocUploads.size());
|
||||
for (OCUpload ocUpload : ocUploads) {
|
||||
|
||||
OCUpload existingUpload = getPendingCurrentOrFailedUpload(ocUpload);
|
||||
if (existingUpload != null) {
|
||||
Log_OC.v(TAG, "Will update upload in db since " + ocUpload.getLocalPath() + " already exists as" +
|
||||
" pending, current or failed upload");
|
||||
ocUpload.setUploadId(existingUpload.getUploadId());
|
||||
updateUpload(ocUpload);
|
||||
continue;
|
||||
}
|
||||
|
||||
final ContentProviderOperation operation = ContentProviderOperation
|
||||
.newInsert(ProviderTableMeta.CONTENT_URI_UPLOADS)
|
||||
.withValues(getContentValues(ocUpload))
|
||||
.build();
|
||||
operations.add(operation);
|
||||
}
|
||||
|
||||
try {
|
||||
final ContentProviderResult[] contentProviderResults = getDB().applyBatch(MainApp.getAuthority(), operations);
|
||||
for (int i = 0; i < contentProviderResults.length; i++) {
|
||||
final ContentProviderResult result = contentProviderResults[i];
|
||||
final long new_id = Long.parseLong(result.uri.getPathSegments().get(1));
|
||||
ocUploads.get(i).setUploadId(new_id);
|
||||
}
|
||||
notifyObserversNow();
|
||||
} catch (OperationApplicationException | RemoteException e) {
|
||||
Log_OC.e(TAG, "Error inserting uploads", e);
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private ContentValues getContentValues(OCUpload ocUpload) {
|
||||
ContentValues cv = new ContentValues();
|
||||
cv.put(ProviderTableMeta.UPLOADS_LOCAL_PATH, ocUpload.getLocalPath());
|
||||
cv.put(ProviderTableMeta.UPLOADS_REMOTE_PATH, ocUpload.getRemotePath());
|
||||
cv.put(ProviderTableMeta.UPLOADS_ACCOUNT_NAME, ocUpload.getAccountName());
|
||||
cv.put(ProviderTableMeta.UPLOADS_FILE_SIZE, ocUpload.getFileSize());
|
||||
cv.put(ProviderTableMeta.UPLOADS_STATUS, ocUpload.getUploadStatus().value);
|
||||
cv.put(ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR, ocUpload.getLocalAction());
|
||||
cv.put(ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY, ocUpload.getNameCollisionPolicy().serialize());
|
||||
cv.put(ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER, ocUpload.isCreateRemoteFolder() ? 1 : 0);
|
||||
cv.put(ProviderTableMeta.UPLOADS_LAST_RESULT, ocUpload.getLastResult().getValue());
|
||||
cv.put(ProviderTableMeta.UPLOADS_CREATED_BY, ocUpload.getCreatedBy());
|
||||
cv.put(ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY, ocUpload.isWhileChargingOnly() ? 1 : 0);
|
||||
cv.put(ProviderTableMeta.UPLOADS_IS_WIFI_ONLY, ocUpload.isUseWifiOnly() ? 1 : 0);
|
||||
cv.put(ProviderTableMeta.UPLOADS_FOLDER_UNLOCK_TOKEN, ocUpload.getFolderUnlockToken());
|
||||
return cv;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update an upload object in DB.
|
||||
*
|
||||
@@ -387,52 +292,6 @@ public class UploadsStorageManager extends Observable {
|
||||
return getUploads(null, (String[]) null);
|
||||
}
|
||||
|
||||
public OCUpload getPendingCurrentOrFailedUpload(OCUpload upload) {
|
||||
try (Cursor cursor = getDB().query(
|
||||
ProviderTableMeta.CONTENT_URI_UPLOADS,
|
||||
null,
|
||||
ProviderTableMeta.UPLOADS_REMOTE_PATH + "=? and " +
|
||||
ProviderTableMeta.UPLOADS_LOCAL_PATH + "=? and " +
|
||||
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + "=? and (" +
|
||||
ProviderTableMeta.UPLOADS_STATUS + "=? or " +
|
||||
ProviderTableMeta.UPLOADS_STATUS + "=? )",
|
||||
new String[]{
|
||||
upload.getRemotePath(),
|
||||
upload.getLocalPath(),
|
||||
upload.getAccountName(),
|
||||
String.valueOf(UploadStatus.UPLOAD_IN_PROGRESS.value),
|
||||
String.valueOf(UploadStatus.UPLOAD_FAILED.value)
|
||||
},
|
||||
ProviderTableMeta.UPLOADS_REMOTE_PATH + " ASC")) {
|
||||
|
||||
if (cursor != null) {
|
||||
if (cursor.moveToFirst()) {
|
||||
return createOCUploadFromCursor(cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public OCUpload getUploadByRemotePath(String remotePath) {
|
||||
OCUpload result = null;
|
||||
try (Cursor cursor = getDB().query(
|
||||
ProviderTableMeta.CONTENT_URI_UPLOADS,
|
||||
null,
|
||||
ProviderTableMeta.UPLOADS_REMOTE_PATH + "=?",
|
||||
new String[]{remotePath},
|
||||
ProviderTableMeta.UPLOADS_REMOTE_PATH + " ASC")) {
|
||||
|
||||
if (cursor != null) {
|
||||
if (cursor.moveToFirst()) {
|
||||
result = createOCUploadFromCursor(cursor);
|
||||
}
|
||||
}
|
||||
}
|
||||
Log_OC.d(TAG, "Retrieve job " + result + " for remote path " + remotePath);
|
||||
return result;
|
||||
}
|
||||
|
||||
public @Nullable
|
||||
OCUpload getUploadById(long id) {
|
||||
OCUpload result = null;
|
||||
@@ -508,19 +367,6 @@ public class UploadsStorageManager extends Observable {
|
||||
return getUploadPage(QUERY_PAGE_SIZE, afterId, true, selection, selectionArgs);
|
||||
}
|
||||
|
||||
private String getInProgressAndDelayedUploadsSelection() {
|
||||
return "( " + ProviderTableMeta.UPLOADS_STATUS + EQUAL + UploadStatus.UPLOAD_IN_PROGRESS.value +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_FOR_WIFI.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.LOCK_FAILED.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_FOR_CHARGING.getValue() +
|
||||
OR + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
EQUAL + UploadResult.DELAYED_IN_POWER_SAVE_MODE.getValue() +
|
||||
" ) AND " + ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private List<OCUpload> getUploadPage(long limit, final long afterId, final boolean descending, @Nullable String selection, @Nullable String... selectionArgs) {
|
||||
List<OCUpload> uploads = new ArrayList<>();
|
||||
@@ -630,17 +476,6 @@ public class UploadsStorageManager extends Observable {
|
||||
return upload;
|
||||
}
|
||||
|
||||
public OCUpload[] getCurrentAndPendingUploadsForCurrentAccount() {
|
||||
User user = currentAccountProvider.getUser();
|
||||
|
||||
return getCurrentAndPendingUploadsForAccount(user.getAccountName());
|
||||
}
|
||||
|
||||
public OCUpload[] getCurrentAndPendingUploadsForAccount(final @NonNull String accountName) {
|
||||
String inProgressUploadsSelection = getInProgressAndDelayedUploadsSelection();
|
||||
return getUploads(inProgressUploadsSelection, accountName);
|
||||
}
|
||||
|
||||
public long[] getCurrentUploadIds(final @NonNull String accountName) {
|
||||
final var result = uploadDao.getAllIds(UploadStatus.UPLOAD_IN_PROGRESS.value, accountName);
|
||||
return result.stream()
|
||||
@@ -670,13 +505,6 @@ public class UploadsStorageManager extends Observable {
|
||||
return getUploads(ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL, accountName);
|
||||
}
|
||||
|
||||
public OCUpload[] getFinishedUploadsForCurrentAccount() {
|
||||
User user = currentAccountProvider.getUser();
|
||||
|
||||
return getUploads(ProviderTableMeta.UPLOADS_STATUS + EQUAL + UploadStatus.UPLOAD_SUCCEEDED.value + AND +
|
||||
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL, user.getAccountName());
|
||||
}
|
||||
|
||||
public OCUpload[] getCancelledUploadsForCurrentAccount() {
|
||||
User user = currentAccountProvider.getUser();
|
||||
|
||||
@@ -684,22 +512,6 @@ public class UploadsStorageManager extends Observable {
|
||||
ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL, user.getAccountName());
|
||||
}
|
||||
|
||||
public OCUpload[] getFailedButNotDelayedUploadsForCurrentAccount() {
|
||||
User user = currentAccountProvider.getUser();
|
||||
|
||||
return getUploads(ProviderTableMeta.UPLOADS_STATUS + EQUAL + UploadStatus.UPLOAD_FAILED.value +
|
||||
AND + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
ANGLE_BRACKETS + UploadResult.DELAYED_FOR_WIFI.getValue() +
|
||||
AND + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
ANGLE_BRACKETS + UploadResult.LOCK_FAILED.getValue() +
|
||||
AND + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
ANGLE_BRACKETS + UploadResult.DELAYED_FOR_CHARGING.getValue() +
|
||||
AND + ProviderTableMeta.UPLOADS_LAST_RESULT +
|
||||
ANGLE_BRACKETS + UploadResult.DELAYED_IN_POWER_SAVE_MODE.getValue() +
|
||||
AND + ProviderTableMeta.UPLOADS_ACCOUNT_NAME + IS_EQUAL,
|
||||
user.getAccountName());
|
||||
}
|
||||
|
||||
private ContentResolver getDB() {
|
||||
return contentResolver;
|
||||
}
|
||||
@@ -797,7 +609,7 @@ public class UploadsStorageManager extends Observable {
|
||||
upload.getRemotePath(),
|
||||
localPath
|
||||
);
|
||||
} else {
|
||||
} else if (uploadResult.getCode() != RemoteOperationResult.ResultCode.USER_CANCELLED){
|
||||
updateUploadStatus(
|
||||
upload.getOCUploadId(),
|
||||
UploadStatus.UPLOAD_FAILED,
|
||||
|
||||
@@ -434,7 +434,7 @@ public class FileMenuFilter {
|
||||
|
||||
private boolean anyFileUploading() {
|
||||
for (OCFile file : files) {
|
||||
if (FileUploadHelper.Companion.instance().isUploading(user, file)) {
|
||||
if (FileUploadHelper.Companion.instance().isUploading(file.getRemotePath(), user.getAccountName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ import com.owncloud.android.utils.MimeTypeUtil;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* Remote operation performing the rename of a remote file (or folder?) in the ownCloud server.
|
||||
@@ -161,26 +164,32 @@ public class RenameFileOperation extends SyncOperation {
|
||||
}
|
||||
// create a test file
|
||||
String tmpFolderName = FileStorageUtils.getTemporalPath("");
|
||||
File testFile = new File(tmpFolderName + newName);
|
||||
File tmpFolder = testFile.getParentFile();
|
||||
if (!tmpFolder.exists() && !tmpFolder.mkdirs()) {
|
||||
Log_OC.e(TAG, "Unable to create parent folder " + tmpFolder.getAbsolutePath());
|
||||
Path testFile = Paths.get(tmpFolderName, newName);
|
||||
Path tmpFolder = testFile.getParent();
|
||||
if (tmpFolder != null && !Files.exists(tmpFolder)) {
|
||||
try {
|
||||
Files.createDirectories(tmpFolder);
|
||||
} catch (IOException e) {
|
||||
Log_OC.e(TAG, "Unable to create parent folder " + tmpFolder.toAbsolutePath());
|
||||
}
|
||||
}
|
||||
if (!tmpFolder.isDirectory()) {
|
||||
if (tmpFolder != null && !Files.isDirectory(tmpFolder)) {
|
||||
throw new IOException("Unexpected error: temporal directory could not be created");
|
||||
}
|
||||
try {
|
||||
testFile.createNewFile(); // return value is ignored; it could be 'false' because
|
||||
// the file already existed, that doesn't invalidate the name
|
||||
} catch (IOException e) {
|
||||
Files.createFile(testFile);
|
||||
} catch (Exception e) {
|
||||
Log_OC.i(TAG, "Test for validity of name " + newName + " in the file system failed");
|
||||
return false;
|
||||
}
|
||||
boolean result = testFile.exists() && testFile.isFile();
|
||||
boolean result = Files.exists(testFile) && Files.isRegularFile(testFile);
|
||||
|
||||
// cleaning ; result is ignored, since there is not much we could do in case of failure,
|
||||
// but repeat and repeat...
|
||||
testFile.delete();
|
||||
try {
|
||||
Files.deleteIfExists(testFile);
|
||||
} catch (Exception e) {
|
||||
Log_OC.e("Error deleting file: ", e.getMessage());
|
||||
return true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,6 @@ import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.ReadFolderRemoteOperation;
|
||||
import com.owncloud.android.lib.resources.files.model.RemoteFile;
|
||||
import com.owncloud.android.lib.resources.status.E2EVersion;
|
||||
import com.owncloud.android.operations.common.SyncOperation;
|
||||
import com.owncloud.android.services.OperationsService;
|
||||
import com.owncloud.android.utils.FileStorageUtils;
|
||||
@@ -485,7 +484,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
|
||||
Log_OC.d(TAG, "Exception caught at startDirectDownloads" + e);
|
||||
}
|
||||
} else {
|
||||
mFilesForDirectDownload.forEach(file -> fileDownloadHelper.downloadFile(user, file));
|
||||
fileDownloadHelper.downloadFolder(mLocalFolder, user.getAccountName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -79,12 +79,11 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
@@ -245,7 +244,7 @@ public class UploadFileOperation extends SyncOperation {
|
||||
"Illegal file in UploadFileOperation; storage path invalid: "
|
||||
+ upload.getLocalPath());
|
||||
}
|
||||
|
||||
Log_OC.d(TAG, "creating upload file operation, user: " + user.getAccountName() + " upload account name " + upload.getAccountName());
|
||||
this.uploadsStorageManager = uploadsStorageManager;
|
||||
this.connectivityService = connectivityService;
|
||||
this.powerManagementService = powerManagementService;
|
||||
@@ -971,11 +970,14 @@ public class UploadFileOperation extends SyncOperation {
|
||||
File originalFile = new File(mOriginalStoragePath);
|
||||
File expectedFile = null;
|
||||
FileLock fileLock = null;
|
||||
FileChannel channel = null;
|
||||
|
||||
long size;
|
||||
|
||||
try {
|
||||
// check conditions
|
||||
result = checkConditions(originalFile);
|
||||
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
@@ -983,6 +985,7 @@ public class UploadFileOperation extends SyncOperation {
|
||||
// check name collision
|
||||
final var collisionResult = checkNameCollision(null, client, null, false);
|
||||
if (collisionResult != null) {
|
||||
result = collisionResult;
|
||||
return collisionResult;
|
||||
}
|
||||
|
||||
@@ -994,73 +997,19 @@ public class UploadFileOperation extends SyncOperation {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Get timestamps
|
||||
// Get the last modification date of the file from the file system
|
||||
long lastModifiedTimestamp = originalFile.lastModified() / 1000;
|
||||
|
||||
final Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
|
||||
|
||||
try (RandomAccessFile raf = new RandomAccessFile(mFile.getStoragePath(), "rw");
|
||||
FileChannel channel = raf.getChannel()) {
|
||||
try {
|
||||
channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
|
||||
fileLock = channel.tryLock();
|
||||
|
||||
try {
|
||||
size = channel.size();
|
||||
} catch (Exception exception) {
|
||||
Log_OC.e(TAG, "normalUpload, size cannot be determined from channel: " + exception);
|
||||
size = new File(mFile.getStoragePath()).length();
|
||||
}
|
||||
|
||||
updateSize(size);
|
||||
|
||||
// choose upload strategy
|
||||
if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
|
||||
boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
|
||||
mUploadOperation = new ChunkedFileUploadRemoteOperation(
|
||||
mFile.getStoragePath(),
|
||||
mFile.getRemotePath(),
|
||||
mFile.getMimeType(),
|
||||
mFile.getEtagInConflict(),
|
||||
lastModifiedTimestamp,
|
||||
creationTimestamp,
|
||||
onWifiConnection,
|
||||
mDisableRetries
|
||||
);
|
||||
} else {
|
||||
mUploadOperation = new UploadFileRemoteOperation(
|
||||
mFile.getStoragePath(),
|
||||
mFile.getRemotePath(),
|
||||
mFile.getMimeType(),
|
||||
mFile.getEtagInConflict(),
|
||||
lastModifiedTimestamp,
|
||||
creationTimestamp,
|
||||
mDisableRetries
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the onTransferProgress in FileUploadWorker
|
||||
* {@link FileUploadWorker#onTransferProgress(long, long, long, String)()}
|
||||
*/
|
||||
for (OnDatatransferProgressListener listener : mDataTransferListeners) {
|
||||
mUploadOperation.addDataTransferProgressListener(listener);
|
||||
}
|
||||
|
||||
if (mCancellationRequested.get()) {
|
||||
throw new OperationCancelledException();
|
||||
}
|
||||
|
||||
if (result.isSuccess() && mUploadOperation != null) {
|
||||
result = mUploadOperation.execute(client);
|
||||
|
||||
// move local temporal file or original file to its corresponding
|
||||
// location in the Nextcloud local folder
|
||||
if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
|
||||
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
|
||||
}
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
// Handle SD card case (copy to temp dir, lock there)
|
||||
String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext)
|
||||
+ mFile.getRemotePath();
|
||||
// this basically means that the file is on SD card
|
||||
// try to copy file to temporary dir if it doesn't exist
|
||||
String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext) +
|
||||
mFile.getRemotePath();
|
||||
mFile.setStoragePath(temporalPath);
|
||||
temporalFile = new File(temporalPath);
|
||||
|
||||
@@ -1069,16 +1018,66 @@ public class UploadFileOperation extends SyncOperation {
|
||||
|
||||
if (result.isSuccess()) {
|
||||
if (temporalFile.length() == originalFile.length()) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw");
|
||||
FileChannel channel = raf.getChannel()) {
|
||||
fileLock = channel.tryLock();
|
||||
}
|
||||
channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
|
||||
fileLock = channel.tryLock();
|
||||
} else {
|
||||
result = new RemoteOperationResult<>(ResultCode.LOCK_FAILED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
size = channel.size();
|
||||
} catch (Exception exception) {
|
||||
Log_OC.e(TAG, "normalUpload, size cannot be determined from channel: " + exception);
|
||||
size = new File(mFile.getStoragePath()).length();
|
||||
}
|
||||
|
||||
updateSize(size);
|
||||
|
||||
// perform the upload
|
||||
if (size > ChunkedFileUploadRemoteOperation.CHUNK_SIZE_MOBILE) {
|
||||
boolean onWifiConnection = connectivityService.getConnectivity().isWifi();
|
||||
|
||||
mUploadOperation = new ChunkedFileUploadRemoteOperation(mFile.getStoragePath(),
|
||||
mFile.getRemotePath(),
|
||||
mFile.getMimeType(),
|
||||
mFile.getEtagInConflict(),
|
||||
lastModifiedTimestamp,
|
||||
creationTimestamp,
|
||||
onWifiConnection,
|
||||
mDisableRetries);
|
||||
} else {
|
||||
mUploadOperation = new UploadFileRemoteOperation(mFile.getStoragePath(),
|
||||
mFile.getRemotePath(),
|
||||
mFile.getMimeType(),
|
||||
mFile.getEtagInConflict(),
|
||||
lastModifiedTimestamp,
|
||||
creationTimestamp,
|
||||
mDisableRetries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the onTransferProgress in FileUploadWorker
|
||||
* {@link FileUploadWorker#onTransferProgress(long, long, long, String)()}
|
||||
*/
|
||||
for (OnDatatransferProgressListener mDataTransferListener : mDataTransferListeners) {
|
||||
mUploadOperation.addDataTransferProgressListener(mDataTransferListener);
|
||||
}
|
||||
|
||||
if (mCancellationRequested.get()) {
|
||||
throw new OperationCancelledException();
|
||||
}
|
||||
|
||||
if (result.isSuccess() && mUploadOperation != null) {
|
||||
result = mUploadOperation.execute(client);
|
||||
|
||||
/// move local temporal file or original file to its corresponding
|
||||
// location in the Nextcloud local folder
|
||||
if (!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
|
||||
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
|
||||
}
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
Log_OC.d(TAG, mOriginalStoragePath + " not exists anymore");
|
||||
result = new RemoteOperationResult<>(ResultCode.LOCAL_FILE_NOT_FOUND);
|
||||
@@ -1098,7 +1097,14 @@ public class UploadFileOperation extends SyncOperation {
|
||||
}
|
||||
}
|
||||
|
||||
// delete temporal file
|
||||
if (channel != null) {
|
||||
try {
|
||||
channel.close();
|
||||
} catch (IOException e) {
|
||||
Log_OC.w(TAG, "Failed to close file channel");
|
||||
}
|
||||
}
|
||||
|
||||
if (temporalFile != null && !originalFile.equals(temporalFile)) {
|
||||
boolean isTempFileDeleted = temporalFile.delete();
|
||||
Log_OC.d(TAG, "normalUpload, temp folder deletion: " + isTempFileDeleted);
|
||||
@@ -1117,6 +1123,7 @@ public class UploadFileOperation extends SyncOperation {
|
||||
getStorageManager().saveConflict(mFile, mFile.getEtagInConflict());
|
||||
}
|
||||
|
||||
// delete temporal file
|
||||
if (temporalFile != null && temporalFile.exists() && !temporalFile.delete()) {
|
||||
Log_OC.e(TAG, "Could not delete temporal file " + temporalFile.getAbsolutePath());
|
||||
}
|
||||
@@ -1427,21 +1434,37 @@ public class UploadFileOperation extends SyncOperation {
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows to cancel the actual upload operation. If actual upload operating is in progress it is cancelled, if
|
||||
* upload preparation is being performed upload will not take place.
|
||||
* Cancels the current upload process.
|
||||
*
|
||||
* <p>
|
||||
* Behavior depends on the current state of the upload:
|
||||
* <ul>
|
||||
* <li><b>Upload in preparation:</b> Upload will not start and a cancellation flag is set.</li>
|
||||
* <li><b>Upload in progress:</b> The ongoing upload operation is cancelled via
|
||||
* {@link UploadFileRemoteOperation#cancel(ResultCode)}.</li>
|
||||
* <li><b>No upload operation:</b> A cancellation flag is still set, but this situation is unexpected
|
||||
* and logged as an error.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* Once cancelled, the database will be updated through
|
||||
* {@link UploadsStorageManager#updateDatabaseUploadResult(RemoteOperationResult, UploadFileOperation)}.
|
||||
*
|
||||
* @param cancellationReason the reason for cancellation
|
||||
*/
|
||||
public void cancel(ResultCode cancellationReason) {
|
||||
if (mUploadOperation == null) {
|
||||
if (mUploadStarted.get()) {
|
||||
Log_OC.d(TAG, "Cancelling upload during upload preparations.");
|
||||
mCancellationRequested.set(true);
|
||||
} else {
|
||||
mCancellationRequested.set(true);
|
||||
Log_OC.e(TAG, "No upload in progress. This should not happen.");
|
||||
}
|
||||
} else {
|
||||
if (mUploadOperation != null) {
|
||||
// Cancel an active upload
|
||||
Log_OC.d(TAG, "Cancelling upload during actual upload operation.");
|
||||
mUploadOperation.cancel(cancellationReason);
|
||||
} else {
|
||||
// Cancel while preparing or when no upload exists
|
||||
mCancellationRequested.set(true);
|
||||
if (mUploadStarted.get()) {
|
||||
Log_OC.d(TAG, "Cancelling upload during preparation.");
|
||||
} else {
|
||||
Log_OC.e(TAG, "No upload in progress. This should not happen.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1552,10 +1575,8 @@ public class UploadFileOperation extends SyncOperation {
|
||||
// try to copy and then delete
|
||||
Files.createFile(targetFile.toPath());
|
||||
try (
|
||||
FileInputStream fis = new FileInputStream(sourceFile);
|
||||
FileOutputStream fos = new FileOutputStream(targetFile);
|
||||
FileChannel inChannel = fis.getChannel();
|
||||
FileChannel outChannel = fos.getChannel()
|
||||
FileChannel inChannel = new FileInputStream(sourceFile).getChannel();
|
||||
FileChannel outChannel = new FileOutputStream(targetFile).getChannel()
|
||||
) {
|
||||
inChannel.transferTo(0, inChannel.size(), outChannel);
|
||||
Files.delete(sourceFile.toPath());
|
||||
|
||||
@@ -189,7 +189,7 @@ public class ActivitiesActivity extends DrawerActivity implements ActivityListIn
|
||||
} else {
|
||||
showEmptyContent(getString(R.string.server_not_reachable),
|
||||
getString(R.string.server_not_reachable_content));
|
||||
binding.emptyList.emptyListIcon.setImageResource(R.drawable.ic_cloud_sync_off);
|
||||
binding.emptyList.emptyListIcon.setImageResource(R.drawable.ic_sync_off);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import android.graphics.drawable.PictureDrawable;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.PersistableBundle;
|
||||
import android.os.SystemClock;
|
||||
import android.text.TextUtils;
|
||||
import android.view.Menu;
|
||||
@@ -115,6 +116,7 @@ import java.util.Optional;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.activity.OnBackPressedCallback;
|
||||
import androidx.annotation.IdRes;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -206,6 +208,12 @@ public abstract class DrawerActivity extends ToolbarActivity
|
||||
@Inject
|
||||
ClientFactory clientFactory;
|
||||
|
||||
@Override
|
||||
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
|
||||
super.onCreate(savedInstanceState, persistentState);
|
||||
addOnBackPressedCallback();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the drawer and its content. This method needs to be called after the content view has been set.
|
||||
*/
|
||||
@@ -1153,19 +1161,24 @@ public abstract class DrawerActivity extends ToolbarActivity
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (isDrawerOpen()) {
|
||||
closeDrawer();
|
||||
return;
|
||||
}
|
||||
Fragment fileDetailsSharingProcessFragment =
|
||||
getSupportFragmentManager().findFragmentByTag(FileDetailsSharingProcessFragment.TAG);
|
||||
if (fileDetailsSharingProcessFragment != null) {
|
||||
((FileDetailsSharingProcessFragment) fileDetailsSharingProcessFragment).onBackPressed();
|
||||
} else {
|
||||
super.onBackPressed();
|
||||
}
|
||||
public void addOnBackPressedCallback() {
|
||||
getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
|
||||
@Override
|
||||
public void handleOnBackPressed() {
|
||||
if (isDrawerOpen()) {
|
||||
closeDrawer();
|
||||
return;
|
||||
}
|
||||
|
||||
final var fragment = getSupportFragmentManager().findFragmentByTag(FileDetailsSharingProcessFragment.TAG);
|
||||
if (fragment instanceof FileDetailsSharingProcessFragment fileDetailsSharingProcessFragment) {
|
||||
fileDetailsSharingProcessFragment.onBackPressed();
|
||||
} else {
|
||||
setEnabled(false);
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -129,6 +129,7 @@ public abstract class FileActivity extends DrawerActivity
|
||||
LoadingVersionNumberTask.VersionDevInterface, FileDetailSharingFragment.OnEditShareListener, NetworkChangeListener {
|
||||
|
||||
public static final String EXTRA_FILE = "com.owncloud.android.ui.activity.FILE";
|
||||
public static final String EXTRA_FILE_REMOTE_PATH = "com.owncloud.android.ui.activity.FILE_REMOTE_PATH";
|
||||
public static final String EXTRA_LIVE_PHOTO_FILE = "com.owncloud.android.ui.activity.LIVE.PHOTO.FILE";
|
||||
public static final String EXTRA_USER = "com.owncloud.android.ui.activity.USER";
|
||||
public static final String EXTRA_FROM_NOTIFICATION = "com.owncloud.android.ui.activity.FROM_NOTIFICATION";
|
||||
|
||||
@@ -40,6 +40,7 @@ import android.view.MenuItem
|
||||
import android.view.View
|
||||
import android.view.ViewTreeObserver.OnGlobalLayoutListener
|
||||
import android.view.WindowManager.BadTokenException
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import androidx.appcompat.widget.SearchView
|
||||
import androidx.core.view.MenuItemCompat
|
||||
@@ -82,6 +83,7 @@ import com.nextcloud.utils.extensions.getParcelableArgument
|
||||
import com.nextcloud.utils.extensions.isActive
|
||||
import com.nextcloud.utils.extensions.lastFragment
|
||||
import com.nextcloud.utils.extensions.logFileSize
|
||||
import com.nextcloud.utils.extensions.navigateToAllFiles
|
||||
import com.nextcloud.utils.fileNameValidator.FileNameValidator.checkFolderPath
|
||||
import com.nextcloud.utils.view.FastScrollUtils
|
||||
import com.owncloud.android.MainApp
|
||||
@@ -155,7 +157,6 @@ import com.owncloud.android.utils.PermissionUtil.requestNotificationPermission
|
||||
import com.owncloud.android.utils.PushUtils
|
||||
import com.owncloud.android.utils.StringUtils
|
||||
import com.owncloud.android.utils.theme.CapabilityUtils
|
||||
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -278,6 +279,7 @@ class FileDisplayActivity :
|
||||
initSyncBroadcastReceiver()
|
||||
observeWorkerState()
|
||||
startMetadataSyncForRoot()
|
||||
handleBackPress()
|
||||
}
|
||||
|
||||
private fun loadSavedInstanceState(savedInstanceState: Bundle?) {
|
||||
@@ -549,7 +551,7 @@ class FileDisplayActivity :
|
||||
|
||||
when {
|
||||
ACTION_DETAILS.equals(action, ignoreCase = true) -> {
|
||||
val file = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
|
||||
val file = getFileFromIntent(intent)
|
||||
setFile(file)
|
||||
showDetails(file)
|
||||
}
|
||||
@@ -578,7 +580,6 @@ class FileDisplayActivity :
|
||||
when (intent.action) {
|
||||
Intent.ACTION_VIEW -> handleOpenFileViaIntent(intent)
|
||||
OPEN_FILE -> {
|
||||
supportFragmentManager.executePendingTransactions()
|
||||
onOpenFileIntent(intent)
|
||||
}
|
||||
}
|
||||
@@ -645,18 +646,41 @@ class FileDisplayActivity :
|
||||
// endregion
|
||||
|
||||
private fun onOpenFileIntent(intent: Intent) {
|
||||
val extra = intent.getStringExtra(EXTRA_FILE)
|
||||
val file = storageManager.getFileByDecryptedRemotePath(extra)
|
||||
if (file != null) {
|
||||
val fileFragment: OCFileListFragment?
|
||||
val leftFragment = this.leftFragment
|
||||
if (leftFragment is OCFileListFragment) {
|
||||
fileFragment = leftFragment
|
||||
} else {
|
||||
fileFragment = OCFileListFragment()
|
||||
this.leftFragment = fileFragment
|
||||
val file = getFileFromIntent(intent)
|
||||
if (file == null) {
|
||||
Log_OC.e(TAG, "Can't open file intent, file is null")
|
||||
return
|
||||
}
|
||||
|
||||
val currentFragment = leftFragment
|
||||
|
||||
if (currentFragment == null) {
|
||||
Log_OC.e(TAG, "Can't open file intent, left fragment is null")
|
||||
return
|
||||
}
|
||||
|
||||
val fileListFragment: OCFileListFragment = when {
|
||||
currentFragment is OCFileListFragment && currentFragment !is GalleryFragment -> {
|
||||
currentFragment
|
||||
}
|
||||
fileFragment.onItemClicked(file)
|
||||
|
||||
else -> {
|
||||
Log_OC.w(
|
||||
TAG,
|
||||
"Left fragment is not a valid OCFileListFragment " +
|
||||
"(was ${currentFragment::class.simpleName}). " +
|
||||
"Replacing with OCFileListFragment."
|
||||
)
|
||||
val newFragment = OCFileListFragment()
|
||||
setLeftFragment(newFragment, false)
|
||||
setupHomeSearchToolbarWithSortAndListButtons()
|
||||
newFragment
|
||||
}
|
||||
}
|
||||
|
||||
// Post to main thread to ensure fragment is fully attached before interacting
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
fileListFragment.onItemClicked(file)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -935,7 +959,7 @@ class FileDisplayActivity :
|
||||
) {
|
||||
openDrawer()
|
||||
} else {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
} else if (itemId == R.id.action_select_all) {
|
||||
val fragment = this.listOfFilesFragment
|
||||
@@ -1136,40 +1160,59 @@ class FileDisplayActivity :
|
||||
}
|
||||
}
|
||||
|
||||
private val isRootDirectory: Boolean
|
||||
get() {
|
||||
val currentDir = getCurrentDir()
|
||||
return (currentDir == null || currentDir.parentId == FileDataStorageManager.ROOT_PARENT_ID.toLong())
|
||||
}
|
||||
|
||||
/*
|
||||
* BackPressed priority/hierarchy:
|
||||
* 1. close search view if opened
|
||||
* 2. close drawer if opened
|
||||
* 3. if it is OCFileListFragment and it's in Root -> (finish Activity) or it's not Root -> (browse up)
|
||||
* 4. otherwise pop up the fragment and sortGroup view visibility and call super.onBackPressed()
|
||||
/**
|
||||
* Sets up a custom back-press handler for this activity.
|
||||
*
|
||||
* This callback determines how the back button behaves based on the current UI state:
|
||||
* - If the search view is open, it closes it.
|
||||
* - If the navigation drawer is open, it closes it.
|
||||
* - If the left fragment is an [OCFileListFragment]:
|
||||
* - If in the root directory, it either navigates to "All Files" or finishes the activity.
|
||||
* - Otherwise, it navigates one level up.
|
||||
* - Otherwise, it pops the current fragment from the back stack.
|
||||
*
|
||||
* ### About `isEnabled`
|
||||
* `isEnabled` is a property of [OnBackPressedCallback].
|
||||
* When `isEnabled = false`, this callback is **temporarily disabled**,
|
||||
* allowing the system or other callbacks to handle the back press instead.
|
||||
*/
|
||||
@SuppressFBWarnings("ITC_INHERITANCE_TYPE_CHECKING") // TODO Apply fail fast principle
|
||||
override fun onBackPressed() {
|
||||
if (isSearchOpen()) {
|
||||
resetSearchAction()
|
||||
return
|
||||
}
|
||||
private fun handleBackPress() {
|
||||
onBackPressedDispatcher.addCallback(
|
||||
this,
|
||||
object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
when {
|
||||
isSearchOpen() -> {
|
||||
isEnabled = false
|
||||
resetSearchAction()
|
||||
}
|
||||
|
||||
if (isDrawerOpen) {
|
||||
super.onBackPressed()
|
||||
return
|
||||
}
|
||||
isDrawerOpen -> {
|
||||
isEnabled = false
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
|
||||
if (this.leftFragment is OCFileListFragment) {
|
||||
if (isRoot(getCurrentDir())) {
|
||||
finish()
|
||||
} else {
|
||||
browseUp(leftFragment as OCFileListFragment)
|
||||
leftFragment is OCFileListFragment -> {
|
||||
val fragment = leftFragment as OCFileListFragment
|
||||
if (isRoot(getCurrentDir())) {
|
||||
if (fragment.shouldNavigateBackToAllFiles()) {
|
||||
navigateToAllFiles()
|
||||
} else {
|
||||
finish()
|
||||
}
|
||||
} else {
|
||||
browseUp(fragment)
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
isEnabled = false
|
||||
popBack()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
popBack()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun browseUp(listOfFiles: OCFileListFragment) {
|
||||
@@ -1200,9 +1243,10 @@ class FileDisplayActivity :
|
||||
|
||||
if (isRoot(getCurrentDir()) && leftFragment is OCFileListFragment) {
|
||||
// Remove the list to the original state
|
||||
|
||||
val listOfHiddenFiles = leftFragment.adapter.listOfHiddenFiles
|
||||
leftFragment.performSearch("", listOfHiddenFiles, true)
|
||||
leftFragment.adapter?.let { adapter ->
|
||||
val listOfHiddenFiles = adapter.listOfHiddenFiles
|
||||
leftFragment.performSearch("", listOfHiddenFiles, true)
|
||||
}
|
||||
|
||||
hideSearchView(getCurrentDir())
|
||||
setDrawerIndicatorEnabled(isDrawerIndicatorAvailable)
|
||||
@@ -1210,20 +1254,20 @@ class FileDisplayActivity :
|
||||
|
||||
if (leftFragment is UnifiedSearchFragment) {
|
||||
showSortListGroup(false)
|
||||
super.onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use this method when want to pop the fragment on back press. It resets Scrolling (See
|
||||
* [with true][.resetScrolling] and pop the visibility for sortListGroup (See
|
||||
* [with false][.showSortListGroup]. At last call to super.onBackPressed()
|
||||
* [with false][.showSortListGroup]. At last call to onBackPressedDispatcher.onBackPressed()
|
||||
*/
|
||||
private fun popBack() {
|
||||
binding.fabMain.setImageResource(R.drawable.ic_plus)
|
||||
resetScrolling(true)
|
||||
showSortListGroup(false)
|
||||
super.onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
@@ -1269,11 +1313,8 @@ class FileDisplayActivity :
|
||||
|
||||
var startFile: OCFile? = null
|
||||
if (intent != null) {
|
||||
val fileArgs = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
|
||||
if (fileArgs != null) {
|
||||
startFile = fileArgs
|
||||
file = startFile
|
||||
}
|
||||
startFile = getFileFromIntent(intent)
|
||||
file = startFile
|
||||
}
|
||||
|
||||
// refresh list of files
|
||||
@@ -1314,6 +1355,11 @@ class FileDisplayActivity :
|
||||
}, ON_RESUMED_RESET_DELAY)
|
||||
}
|
||||
|
||||
private fun getFileFromIntent(intent: Intent?): OCFile? =
|
||||
intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
|
||||
?: intent?.getStringExtra(EXTRA_FILE_REMOTE_PATH)
|
||||
?.let { fileDataStorageManager.getFileByDecryptedRemotePath(it) }
|
||||
|
||||
private fun checkAndSetMenuItemId() {
|
||||
if (MainApp.isOnlyPersonFiles()) {
|
||||
menuItemId = R.id.nav_personal_files
|
||||
@@ -1645,7 +1691,7 @@ class FileDisplayActivity :
|
||||
if (uploadWasFine || file != null && file.fileExists()) {
|
||||
fileDetailFragment.updateFileDetails(false, true)
|
||||
} else {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
|
||||
// Force the preview if the file is an image or text file
|
||||
|
||||
@@ -106,7 +106,7 @@ open class FolderPickerActivity :
|
||||
|
||||
updateActionBarTitleAndHomeButtonByString(captionText)
|
||||
setBackgroundText()
|
||||
handleOnBackPressed()
|
||||
handleBackPress()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
@@ -151,7 +151,7 @@ open class FolderPickerActivity :
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleOnBackPressed() {
|
||||
private fun handleBackPress() {
|
||||
onBackPressedDispatcher.addCallback(
|
||||
this,
|
||||
object : OnBackPressedCallback(true) {
|
||||
@@ -327,7 +327,7 @@ open class FolderPickerActivity :
|
||||
} else if (itemId == android.R.id.home) {
|
||||
val currentDir = currentFolder
|
||||
if (currentDir != null && currentDir.parentId != 0L) {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
} else {
|
||||
retval = super.onOptionsItemSelected(item)
|
||||
|
||||
@@ -201,7 +201,7 @@ class InternalTwoWaySyncActivity :
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||
when (item.itemId) {
|
||||
android.R.id.home -> {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
R.id.action_dismiss_two_way_sync -> {
|
||||
disableTwoWaySyncAndWorkers()
|
||||
|
||||
@@ -91,7 +91,7 @@ class ManageAccountsActivity :
|
||||
multipleAccountsSupported = multiAccountSupport(this)
|
||||
|
||||
setupUserList()
|
||||
handleOnBackPressed()
|
||||
handleBackPress()
|
||||
}
|
||||
|
||||
private fun setupUsers() {
|
||||
@@ -149,7 +149,7 @@ class ManageAccountsActivity :
|
||||
performAccountRemoval(user)
|
||||
}
|
||||
|
||||
private fun handleOnBackPressed() {
|
||||
private fun handleBackPress() {
|
||||
onBackPressedDispatcher.addCallback(
|
||||
this,
|
||||
onBackPressedCallback
|
||||
@@ -160,13 +160,13 @@ class ManageAccountsActivity :
|
||||
override fun handleOnBackPressed() {
|
||||
val resultIntent = Intent()
|
||||
|
||||
if (accountManager.allUsers.size > 0) {
|
||||
if (accountManager.allUsers.isNotEmpty()) {
|
||||
resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, hasAccountListChanged())
|
||||
resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, hasCurrentAccountChanged())
|
||||
setResult(RESULT_OK, resultIntent)
|
||||
} else {
|
||||
val intent = Intent(this@ManageAccountsActivity, AuthenticatorActivity::class.java)
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
startActivity(intent)
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@ class ManageAccountsActivity :
|
||||
var result = true
|
||||
|
||||
if (item.itemId == android.R.id.home) {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
} else {
|
||||
result = super.onOptionsItemSelected(item)
|
||||
}
|
||||
@@ -331,7 +331,7 @@ class ManageAccountsActivity :
|
||||
)
|
||||
recyclerView?.adapter = userListAdapter
|
||||
} else {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -393,8 +393,7 @@ class ManageAccountsActivity :
|
||||
resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, true)
|
||||
resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, true)
|
||||
setResult(RESULT_OK, resultIntent)
|
||||
|
||||
super.onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-11
@@ -103,6 +103,7 @@ import java.util.concurrent.Executors;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import androidx.activity.OnBackPressedCallback;
|
||||
import androidx.annotation.DrawableRes;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
@@ -203,6 +204,8 @@ public class ReceiveExternalFilesActivity extends FileActivity
|
||||
fm.beginTransaction()
|
||||
.add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
|
||||
} // else, Fragment already created and retained across configuration change
|
||||
|
||||
handleBackPress();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -656,14 +659,19 @@ public class ReceiveExternalFilesActivity extends FileActivity
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
if (mParents.size() <= SINGLE_PARENT) {
|
||||
super.onBackPressed();
|
||||
} else {
|
||||
mParents.pop();
|
||||
browseToFolderIfItExists();
|
||||
}
|
||||
private void handleBackPress() {
|
||||
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||
@Override
|
||||
public void handleOnBackPressed() {
|
||||
if (mParents.size() <= SINGLE_PARENT) {
|
||||
setEnabled(false);
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
} else {
|
||||
mParents.pop();
|
||||
browseToFolderIfItExists();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -874,7 +882,9 @@ public class ReceiveExternalFilesActivity extends FileActivity
|
||||
|
||||
private List<OCFile> sortFileList(List<OCFile> files) {
|
||||
FileSortOrder sortOrder = preferences.getSortOrderByFolder(mFile);
|
||||
return sortOrder.sortCloudFiles(files);
|
||||
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
|
||||
boolean favoritesFirst = preferences.isSortFavoritesFirst();
|
||||
return sortOrder.sortCloudFiles(files, foldersBeforeFiles, favoritesFirst);
|
||||
}
|
||||
|
||||
private String generatePath(Stack<String> dirs) {
|
||||
@@ -944,7 +954,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
|
||||
}
|
||||
|
||||
if (mStreamsToUpload.size() > FileUploadHelper.MAX_FILE_COUNT) {
|
||||
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
|
||||
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1097,7 +1107,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
|
||||
dialog.show(getSupportFragmentManager(), CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
|
||||
} else if (itemId == android.R.id.home) {
|
||||
if (mParents.size() > SINGLE_PARENT) {
|
||||
onBackPressed();
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
} else if (itemId == R.id.action_switch_account) {
|
||||
showAccountChooserDialog();
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.activity;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
@@ -183,6 +184,9 @@ public class SettingsActivity extends PreferenceActivity
|
||||
// Synced folders
|
||||
setupAutoUploadCategory(preferenceScreen);
|
||||
|
||||
// Files
|
||||
setupFilesCategory();
|
||||
|
||||
// Details
|
||||
setupDetailsCategory(preferenceScreen);
|
||||
|
||||
@@ -354,6 +358,7 @@ public class SettingsActivity extends PreferenceActivity
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("GestureBackNavigation")
|
||||
@Override
|
||||
public void onBackPressed() {
|
||||
DrawerActivity.menuItemId = R.id.nav_all_files;
|
||||
@@ -661,25 +666,33 @@ public class SettingsActivity extends PreferenceActivity
|
||||
|
||||
boolean fPassCodeEnabled = getResources().getBoolean(R.bool.passcode_enabled);
|
||||
boolean fDeviceCredentialsEnabled = getResources().getBoolean(R.bool.device_credentials_enabled);
|
||||
boolean fShowHiddenFilesEnabled = getResources().getBoolean(R.bool.show_hidden_files_enabled);
|
||||
boolean fShowEcosystemAppsEnabled = !getResources().getBoolean(R.bool.is_branded_client);
|
||||
boolean fSyncedFolderLightEnabled = getResources().getBoolean(R.bool.syncedFolder_light);
|
||||
boolean fShowMediaScanNotifications = preferences.isShowMediaScanNotifications();
|
||||
|
||||
setupLockPreference(preferenceCategoryDetails, fPassCodeEnabled, fDeviceCredentialsEnabled);
|
||||
|
||||
setupHiddenFilesPreference(preferenceCategoryDetails, fShowHiddenFilesEnabled);
|
||||
|
||||
setupShowEcosystemAppsPreference(preferenceCategoryDetails, fShowEcosystemAppsEnabled);
|
||||
|
||||
setupShowMediaScanNotifications(preferenceCategoryDetails, fShowMediaScanNotifications);
|
||||
|
||||
if (!fPassCodeEnabled && !fDeviceCredentialsEnabled && !fShowHiddenFilesEnabled && fSyncedFolderLightEnabled
|
||||
if (!fPassCodeEnabled && !fDeviceCredentialsEnabled && fSyncedFolderLightEnabled
|
||||
&& fShowMediaScanNotifications) {
|
||||
preferenceScreen.removePreference(preferenceCategoryDetails);
|
||||
}
|
||||
}
|
||||
|
||||
private void setupFilesCategory() {
|
||||
PreferenceCategory preferenceCategoryDetails = (PreferenceCategory) findPreference("files");
|
||||
viewThemeUtils.files.themePreferenceCategory(preferenceCategoryDetails);
|
||||
|
||||
boolean fShowHiddenFilesEnabled = getResources().getBoolean(R.bool.show_hidden_files_enabled);
|
||||
|
||||
setupHiddenFilesPreference(preferenceCategoryDetails, fShowHiddenFilesEnabled);
|
||||
setupFoldersBeforeFilesPreference();
|
||||
setupSortFavoritesFirstPreference();
|
||||
}
|
||||
|
||||
private void setupShowMediaScanNotifications(PreferenceCategory preferenceCategoryDetails,
|
||||
boolean fShowMediaScanNotifications) {
|
||||
ThemeableSwitchPreference mShowMediaScanNotifications =
|
||||
@@ -703,6 +716,22 @@ public class SettingsActivity extends PreferenceActivity
|
||||
}
|
||||
}
|
||||
|
||||
private void setupFoldersBeforeFilesPreference() {
|
||||
ThemeableSwitchPreference preference = (ThemeableSwitchPreference) findPreference("sort_folders_before_files");
|
||||
preference.setOnPreferenceClickListener(p -> {
|
||||
preferences.setSortFoldersBeforeFiles(preference.isChecked());
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private void setupSortFavoritesFirstPreference() {
|
||||
ThemeableSwitchPreference preference = (ThemeableSwitchPreference) findPreference("sort_favorites_first");
|
||||
preference.setOnPreferenceClickListener(p -> {
|
||||
preferences.setSortFavoritesFirst(preference.isChecked());
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private void setupShowEcosystemAppsPreference(PreferenceCategory preferenceCategoryDetails, boolean fShowEcosystemAppsEnabled) {
|
||||
showEcosystemApps = (ThemeableSwitchPreference) findPreference("show_ecosystem_apps");
|
||||
if (fShowEcosystemAppsEnabled) {
|
||||
|
||||
@@ -28,6 +28,7 @@ import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.google.android.material.dialog.MaterialAlertDialogBuilder
|
||||
import com.nextcloud.client.appinfo.AppInfo
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.di.Injectable
|
||||
@@ -146,6 +147,9 @@ class SyncedFoldersActivity :
|
||||
@Inject
|
||||
lateinit var syncedFolderProvider: SyncedFolderProvider
|
||||
|
||||
@Inject
|
||||
lateinit var appInfo: AppInfo
|
||||
|
||||
lateinit var binding: SyncedFoldersLayoutBinding
|
||||
lateinit var adapter: SyncedFolderAdapter
|
||||
|
||||
@@ -231,7 +235,8 @@ class SyncedFoldersActivity :
|
||||
this,
|
||||
lightVersion,
|
||||
viewThemeUtils,
|
||||
powerManagementService
|
||||
powerManagementService,
|
||||
connectivityService
|
||||
)
|
||||
binding.emptyList.emptyListIcon.setImageResource(R.drawable.nav_synced_folders)
|
||||
viewThemeUtils.material.colorMaterialButtonPrimaryFilled(binding.emptyList.emptyListViewAction)
|
||||
@@ -561,7 +566,7 @@ class SyncedFoldersActivity :
|
||||
}
|
||||
}
|
||||
if (syncedFolderDisplayItem.isEnabled) {
|
||||
backgroundJobManager.startImmediateFilesSyncJob(syncedFolderDisplayItem, overridePowerSaving = false)
|
||||
backgroundJobManager.startAutoUploadImmediately(syncedFolderDisplayItem, overridePowerSaving = false)
|
||||
showBatteryOptimizationInfo()
|
||||
}
|
||||
}
|
||||
@@ -724,7 +729,7 @@ class SyncedFoldersActivity :
|
||||
// existing synced folder setup to be updated
|
||||
syncedFolderProvider.updateSyncFolder(item)
|
||||
if (item.isEnabled) {
|
||||
backgroundJobManager.startImmediateFilesSyncJob(item, overridePowerSaving = false)
|
||||
backgroundJobManager.startAutoUploadImmediately(item, overridePowerSaving = false)
|
||||
} else {
|
||||
val syncedFolderInitiatedKey = KEY_SYNCED_FOLDER_INITIATED_PREFIX + item.id
|
||||
val arbitraryDataProvider =
|
||||
@@ -741,7 +746,7 @@ class SyncedFoldersActivity :
|
||||
if (storedId != -1L) {
|
||||
item.id = storedId
|
||||
if (item.isEnabled) {
|
||||
backgroundJobManager.startImmediateFilesSyncJob(item, overridePowerSaving = false)
|
||||
backgroundJobManager.startAutoUploadImmediately(item, overridePowerSaving = false)
|
||||
} else {
|
||||
val syncedFolderInitiatedKey = KEY_SYNCED_FOLDER_INITIATED_PREFIX + item.id
|
||||
arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey)
|
||||
@@ -857,7 +862,7 @@ class SyncedFoldersActivity :
|
||||
val powerManager = getSystemService(POWER_SERVICE) as PowerManager?
|
||||
return when {
|
||||
powerManager != null -> !powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID)
|
||||
else -> true
|
||||
else -> !appInfo.isDebugBuild
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,17 +157,32 @@ public abstract class ToolbarActivity extends BaseActivity implements Injectable
|
||||
* Updates title bar and home buttons (state and icon).
|
||||
*/
|
||||
protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
|
||||
String title;
|
||||
boolean isRoot = isRoot(chosenFile);
|
||||
|
||||
title = isRoot ? themeUtils.getDefaultDisplayNameForRootFolder(this) : fileDataStorageManager.getFilenameConsideringOfflineOperation(chosenFile);
|
||||
String title = getActionBarTitle(chosenFile, isRoot);
|
||||
updateActionBarTitleAndHomeButtonByString(title);
|
||||
|
||||
if (mAppBar != null) {
|
||||
showHomeSearchToolbar(title, isRoot);
|
||||
}
|
||||
}
|
||||
|
||||
private String getActionBarTitle(OCFile chosenFile, boolean isRoot) {
|
||||
if (isRoot) {
|
||||
return themeUtils.getDefaultDisplayNameForRootFolder(this);
|
||||
}
|
||||
|
||||
if (chosenFile.isFolder()) {
|
||||
return fileDataStorageManager.getFilenameConsideringOfflineOperation(chosenFile);
|
||||
}
|
||||
|
||||
long parentId = chosenFile.getParentId();
|
||||
OCFile parentFile = fileDataStorageManager.getFileById(parentId);
|
||||
if (parentFile == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return fileDataStorageManager.getFilenameConsideringOfflineOperation(parentFile);
|
||||
}
|
||||
|
||||
public void showSearchView() {
|
||||
if (isHomeSearchToolbarShow) {
|
||||
showHomeSearchToolbar(false);
|
||||
@@ -272,11 +287,21 @@ public abstract class ToolbarActivity extends BaseActivity implements Injectable
|
||||
}
|
||||
|
||||
public void showSortListGroup(boolean show) {
|
||||
findViewById(R.id.sort_list_button_group).setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
final var view = findViewById(R.id.sort_list_button_group);
|
||||
if (view == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
view.setVisibility(show ? View.VISIBLE : View.GONE);
|
||||
}
|
||||
|
||||
public boolean sortListGroupVisibility(){
|
||||
return findViewById(R.id.sort_list_button_group).getVisibility() == View.VISIBLE;
|
||||
final var view = findViewById(R.id.sort_list_button_group);
|
||||
if (view == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return view.getVisibility() == View.VISIBLE;
|
||||
}
|
||||
/**
|
||||
* Change the bitmap for the toolbar's preview image.
|
||||
|
||||
@@ -238,7 +238,7 @@ public class UploadFilesActivity extends DrawerActivity implements LocalFileList
|
||||
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
|
||||
int i = position;
|
||||
while (i-- != 0) {
|
||||
onBackPressed();
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
// the next operation triggers a new call to this method, but it's necessary to
|
||||
// ensure that the name exposed in the action bar is the current directory when the
|
||||
@@ -311,7 +311,7 @@ public class UploadFilesActivity extends DrawerActivity implements LocalFileList
|
||||
|
||||
if (itemId == android.R.id.home) {
|
||||
if (mCurrentDir != null && mCurrentDir.getParentFile() != null) {
|
||||
onBackPressed();
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
} else if (itemId == R.id.action_select_all) {
|
||||
mSelectAll = !item.isChecked();
|
||||
@@ -503,7 +503,7 @@ public class UploadFilesActivity extends DrawerActivity implements LocalFileList
|
||||
} else {
|
||||
final var chosenFiles = mFileListFragment.getCheckedFilePaths();
|
||||
if (chosenFiles.length > FileUploadHelper.MAX_FILE_COUNT) {
|
||||
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
|
||||
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -670,7 +670,7 @@ public class UploadFilesActivity extends DrawerActivity implements LocalFileList
|
||||
} else {
|
||||
final var chosenFiles = mFileListFragment.getCheckedFilePaths();
|
||||
if (chosenFiles.length > FileUploadHelper.MAX_FILE_COUNT) {
|
||||
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
|
||||
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
|
||||
return;
|
||||
}
|
||||
boolean isPositionZero = (binding.uploadFilesSpinnerBehaviour.getSelectedItemPosition() == 0);
|
||||
@@ -720,7 +720,7 @@ public class UploadFilesActivity extends DrawerActivity implements LocalFileList
|
||||
Log_OC.d(TAG, "Positive button in dialog was clicked; dialog tag is " + callerTag);
|
||||
final var chosenFiles = mFileListFragment.getCheckedFilePaths();
|
||||
if (chosenFiles.length > FileUploadHelper.MAX_FILE_COUNT) {
|
||||
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
|
||||
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -182,10 +182,9 @@ public class UploadListActivity extends FileActivity {
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
FilesSyncHelper.startFilesSyncForAllFolders(syncedFolderProvider,
|
||||
FilesSyncHelper.startAutoUploadImmediately(syncedFolderProvider,
|
||||
backgroundJobManager,
|
||||
true,
|
||||
new String[]{});
|
||||
true);
|
||||
|
||||
if (uploadsStorageManager.getFailedUploads().length > 0) {
|
||||
new Thread(() -> {
|
||||
|
||||
@@ -158,7 +158,7 @@ public class UserInfoActivity extends DrawerActivity implements Injectable {
|
||||
int itemId = item.getItemId();
|
||||
|
||||
if (itemId == android.R.id.home) {
|
||||
onBackPressed();
|
||||
getOnBackPressedDispatcher().onBackPressed();
|
||||
} else if (itemId == R.id.action_open_account) {
|
||||
accountClicked(user.hashCode());
|
||||
} else if (itemId == R.id.action_delete_account) {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.Bitmap;
|
||||
@@ -23,6 +24,7 @@ import android.widget.TextView;
|
||||
|
||||
import com.nextcloud.android.common.ui.theme.utils.ColorRole;
|
||||
import com.nextcloud.client.preferences.AppPreferences;
|
||||
import com.nextcloud.utils.FileHelper;
|
||||
import com.owncloud.android.R;
|
||||
import com.owncloud.android.datamodel.ThumbnailsCacheManager;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
@@ -34,8 +36,6 @@ import com.owncloud.android.utils.theme.ViewThemeUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -69,8 +69,10 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
private static final int VIEWTYPE_FOOTER = 1;
|
||||
private static final int VIEWTYPE_IMAGE = 2;
|
||||
|
||||
private static final int PAGE_SIZE = 50;
|
||||
private int currentOffset = 0;
|
||||
|
||||
public LocalFileListAdapter(boolean localFolderPickerMode,
|
||||
File directory,
|
||||
LocalFileListFragmentInterface localFileListFragmentInterface,
|
||||
AppPreferences preferences,
|
||||
Context context,
|
||||
@@ -83,15 +85,9 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
checkedFiles = new HashSet<>();
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
this.isWithinEncryptedFolder = isWithinEncryptedFolder;
|
||||
|
||||
swapDirectory(directory);
|
||||
setHasStableIds(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return mFiles.size() + 1;
|
||||
}
|
||||
|
||||
public int getFilesCount() {
|
||||
return mFiles.size();
|
||||
}
|
||||
@@ -129,30 +125,39 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
}
|
||||
|
||||
public String[] getCheckedFilesPath() {
|
||||
List<String> result = listFilesRecursive(checkedFiles);
|
||||
List<String> result = FileHelper.INSTANCE.listFilesRecursive(checkedFiles);
|
||||
|
||||
Log_OC.d(TAG, "Returning " + result.size() + " selected files");
|
||||
|
||||
return result.toArray(new String[0]);
|
||||
}
|
||||
|
||||
public List<String> listFilesRecursive(Collection<File> files) {
|
||||
List<String> result = new ArrayList<>();
|
||||
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
result.addAll(listFilesRecursive(getFiles(file)));
|
||||
} else {
|
||||
result.add(file.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return mFiles.size() + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getItemId(int position) {
|
||||
return mFiles.size() <= position ? position : -1;
|
||||
if (position >= mFiles.size()) {
|
||||
return RecyclerView.NO_ID;
|
||||
}
|
||||
|
||||
File file = mFiles.get(position);
|
||||
return file.getAbsolutePath().hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
if (position == mFiles.size()) {
|
||||
return VIEWTYPE_FOOTER;
|
||||
} else {
|
||||
if (MimeTypeUtil.isImageOrVideo(getItem(position))) {
|
||||
return VIEWTYPE_IMAGE;
|
||||
} else {
|
||||
return VIEWTYPE_ITEM;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -271,19 +276,6 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemViewType(int position) {
|
||||
if (position == mFiles.size()) {
|
||||
return VIEWTYPE_FOOTER;
|
||||
} else {
|
||||
if (MimeTypeUtil.isImageOrVideo(getItem(position))) {
|
||||
return VIEWTYPE_IMAGE;
|
||||
} else {
|
||||
return VIEWTYPE_ITEM;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private File getItem(int position) {
|
||||
return mFiles.get(position);
|
||||
}
|
||||
@@ -317,43 +309,81 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
*/
|
||||
public void swapDirectory(final File directory) {
|
||||
localFileListFragmentInterface.setLoading(true);
|
||||
final Handler uiHandler = new Handler(Looper.getMainLooper());
|
||||
currentOffset = 0;
|
||||
mFiles.clear();
|
||||
mFilesAll.clear();
|
||||
|
||||
Executors.newSingleThreadExecutor().execute(() -> {
|
||||
List<File> fileList;
|
||||
if (directory == null) {
|
||||
fileList = new ArrayList<>();
|
||||
} else {
|
||||
if (mLocalFolderPicker) {
|
||||
fileList = getFolders(directory);
|
||||
} else {
|
||||
fileList = getFiles(directory);
|
||||
}
|
||||
// Load first page of folders
|
||||
List<File> firstPage = FileHelper.INSTANCE.listDirectoryEntries(directory, currentOffset, PAGE_SIZE, true);
|
||||
|
||||
if (!firstPage.isEmpty()) {
|
||||
firstPage = sortAndFilterHiddenEntries(firstPage);
|
||||
}
|
||||
|
||||
if (!fileList.isEmpty()) {
|
||||
FileSortOrder sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.localFileListView);
|
||||
fileList = sortOrder.sortLocalFiles(fileList);
|
||||
currentOffset += PAGE_SIZE;
|
||||
updateUIForFirstPage(firstPage);
|
||||
|
||||
// Fetch preferences for showing hidden files
|
||||
boolean showHiddenFiles = preferences.isShowHiddenFilesEnabled();
|
||||
if (!showHiddenFiles) {
|
||||
fileList = filterHiddenFiles(fileList);
|
||||
}
|
||||
}
|
||||
final List<File> newFiles = fileList;
|
||||
// Load remaining folders, then all files
|
||||
loadRemainingEntries(directory, true);
|
||||
|
||||
uiHandler.post(() -> {
|
||||
mFiles = newFiles;
|
||||
mFilesAll = new ArrayList<>();
|
||||
mFilesAll.addAll(mFiles);
|
||||
// Reset for files
|
||||
currentOffset = 0;
|
||||
|
||||
notifyDataSetChanged();
|
||||
localFileListFragmentInterface.setLoading(false);
|
||||
});
|
||||
loadRemainingEntries(directory, false);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private void updateUIForFirstPage(List<File> firstPage) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
mFiles = new ArrayList<>(firstPage);
|
||||
mFilesAll = new ArrayList<>(firstPage);
|
||||
notifyDataSetChanged();
|
||||
localFileListFragmentInterface.setLoading(false);
|
||||
});
|
||||
}
|
||||
|
||||
private List<File> sortAndFilterHiddenEntries(List<File> nextPage) {
|
||||
boolean showHiddenFiles = preferences.isShowHiddenFilesEnabled();
|
||||
FileSortOrder sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.localFileListView);
|
||||
|
||||
if (!showHiddenFiles) {
|
||||
nextPage = filterHiddenFiles(nextPage);
|
||||
}
|
||||
|
||||
return sortOrder.sortLocalFiles(nextPage);
|
||||
}
|
||||
|
||||
private void loadRemainingEntries(File directory, boolean fetchFolders) {
|
||||
while (true) {
|
||||
List<File> nextPage = FileHelper.INSTANCE.listDirectoryEntries(directory, currentOffset, PAGE_SIZE, fetchFolders);
|
||||
if (nextPage.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
|
||||
nextPage = sortAndFilterHiddenEntries(nextPage);
|
||||
|
||||
currentOffset += PAGE_SIZE;
|
||||
notifyItemRange(nextPage);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyItemRange(List<File> updatedList) {
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
int from = mFiles.size();
|
||||
int to = updatedList.size();
|
||||
|
||||
mFiles.addAll(updatedList);
|
||||
mFilesAll.addAll(updatedList);
|
||||
|
||||
Log_OC.d(TAG, "notifyItemRange, item size: " + mFilesAll.size());
|
||||
|
||||
notifyItemRangeInserted(from, to);
|
||||
});
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setSortOrder(FileSortOrder sortOrder) {
|
||||
localFileListFragmentInterface.setLoading(true);
|
||||
final Handler uiHandler = new Handler(Looper.getMainLooper());
|
||||
@@ -366,30 +396,9 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
localFileListFragmentInterface.setLoading(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
private List<File> getFolders(final File directory) {
|
||||
File[] folders = directory.listFiles(File::isDirectory);
|
||||
|
||||
if (folders != null && folders.length > 0) {
|
||||
return new ArrayList<>(Arrays.asList(folders));
|
||||
} else {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
private List<File> getFiles(File directory) {
|
||||
File[] files = directory.listFiles();
|
||||
|
||||
if (files != null && files.length > 0) {
|
||||
return new ArrayList<>(Arrays.asList(files));
|
||||
} else {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void filter(String text) {
|
||||
if (text.isEmpty()) {
|
||||
mFiles = mFilesAll;
|
||||
@@ -514,11 +523,11 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@VisibleForTesting
|
||||
public void setFiles(List<File> newFiles) {
|
||||
mFiles = newFiles;
|
||||
mFilesAll = new ArrayList<>();
|
||||
mFilesAll.addAll(mFiles);
|
||||
mFilesAll = new ArrayList<>(mFiles);
|
||||
|
||||
notifyDataSetChanged();
|
||||
localFileListFragmentInterface.setLoading(false);
|
||||
|
||||
@@ -266,7 +266,9 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
if (searchType == SearchType.SHARED_FILTER) {
|
||||
mFiles.sort((o1, o2) -> Long.compare(o2.getFirstShareTimestamp(), o1.getFirstShareTimestamp()));
|
||||
} else {
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles);
|
||||
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
|
||||
boolean favoritesFirst = preferences.isSortFavoritesFirst();
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
|
||||
}
|
||||
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
@@ -907,7 +909,9 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
mFiles = OCFileExtensionsKt.filterFilenames(mFiles);
|
||||
|
||||
sortOrder = preferences.getSortOrderByFolder(directory);
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles);
|
||||
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
|
||||
boolean favoritesFirst = preferences.isSortFavoritesFirst();
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
|
||||
prepareListOfHiddenFiles();
|
||||
mergeOCFilesForLivePhoto();
|
||||
mFilesAll.clear();
|
||||
@@ -999,15 +1003,18 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
searchType == SearchType.RECENTLY_MODIFIED_SEARCH) {
|
||||
mFiles = FileStorageUtils.sortOcFolderDescDateModifiedWithoutFavoritesFirst(mFiles);
|
||||
} else if (searchType != SearchType.SHARED_FILTER) {
|
||||
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
|
||||
boolean favoritesFirst = preferences.isSortFavoritesFirst();
|
||||
|
||||
if (searchType == SearchType.FAVORITE_SEARCH) {
|
||||
sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.favoritesListView);
|
||||
} else {
|
||||
sortOrder = preferences.getSortOrderByFolder(folder);
|
||||
}
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles);
|
||||
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
|
||||
}
|
||||
|
||||
this.searchType = searchType;
|
||||
|
||||
mFilesAll.clear();
|
||||
mFilesAll.addAll(mFiles);
|
||||
@@ -1134,14 +1141,17 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
|
||||
mStorageManager.saveVirtuals(contentValues);
|
||||
}
|
||||
|
||||
public void setSortOrder(@Nullable OCFile folder, FileSortOrder sortOrder) {
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setSortOrder(@Nullable OCFile folder, @NonNull FileSortOrder sortOrder) {
|
||||
if (searchType == SearchType.FAVORITE_SEARCH) {
|
||||
preferences.setSortOrder(FileSortOrder.Type.favoritesListView, sortOrder);
|
||||
} else {
|
||||
preferences.setSortOrder(folder, sortOrder);
|
||||
}
|
||||
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles);
|
||||
|
||||
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
|
||||
boolean favoritesFirst = preferences.isSortFavoritesFirst();
|
||||
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
|
||||
notifyDataSetChanged();
|
||||
|
||||
this.sortOrder = sortOrder;
|
||||
|
||||
@@ -380,7 +380,7 @@ class OCFileListDelegate(
|
||||
|
||||
return operationsServiceBinder?.isSynchronizing(user, file) == true ||
|
||||
fileDownloadHelper.isDownloading(user, file) ||
|
||||
fileUploadHelper.isUploading(user, file)
|
||||
fileUploadHelper.isUploading(file.remotePath, user.accountName)
|
||||
}
|
||||
|
||||
private fun showLocalFileIndicator(file: OCFile, holder: ListViewHolder) {
|
||||
|
||||
@@ -23,6 +23,8 @@ import com.google.android.material.button.MaterialButton
|
||||
import com.nextcloud.android.common.ui.theme.utils.ColorRole
|
||||
import com.nextcloud.client.core.Clock
|
||||
import com.nextcloud.client.device.PowerManagementService
|
||||
import com.nextcloud.client.network.ConnectivityService
|
||||
import com.nextcloud.utils.extensions.calculateScanInterval
|
||||
import com.nextcloud.utils.extensions.filterEnabledOrWithoutEnabledParent
|
||||
import com.nextcloud.utils.extensions.hasEnabledParent
|
||||
import com.nextcloud.utils.extensions.setVisibleIf
|
||||
@@ -32,6 +34,7 @@ import com.owncloud.android.databinding.SyncedFoldersEmptyBinding
|
||||
import com.owncloud.android.databinding.SyncedFoldersFooterBinding
|
||||
import com.owncloud.android.databinding.SyncedFoldersItemHeaderBinding
|
||||
import com.owncloud.android.datamodel.MediaFolderType
|
||||
import com.owncloud.android.datamodel.SyncedFolder
|
||||
import com.owncloud.android.datamodel.SyncedFolderDisplayItem
|
||||
import com.owncloud.android.datamodel.ThumbnailsCacheManager
|
||||
import com.owncloud.android.datamodel.ThumbnailsCacheManager.AsyncMediaThumbnailDrawable
|
||||
@@ -41,6 +44,7 @@ import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Adapter to display all auto-synced folders and/or instant upload media folders.
|
||||
@@ -53,7 +57,8 @@ class SyncedFolderAdapter(
|
||||
private val clickListener: ClickListener,
|
||||
private val light: Boolean,
|
||||
private val viewThemeUtils: ViewThemeUtils,
|
||||
private val powerManagementService: PowerManagementService
|
||||
private val powerManagementService: PowerManagementService,
|
||||
private val connectivityService: ConnectivityService
|
||||
) : SectionedRecyclerViewAdapter<SectionedViewHolder>() {
|
||||
|
||||
private val gridTotal = gridWidth * 2
|
||||
@@ -62,6 +67,14 @@ class SyncedFolderAdapter(
|
||||
private var hideItems = true
|
||||
private val thumbnailThreadPool: Executor = Executors.newCachedThreadPool()
|
||||
|
||||
private val minimumSizeForTouchableArea
|
||||
by lazy { context.resources.getDimensionPixelSize(R.dimen.minimum_size_for_touchable_area) }
|
||||
private val screenWidth by lazy { context.resources.displayMetrics.widthPixels }
|
||||
private val standardDoubleMargin
|
||||
by lazy { context.resources.getDimensionPixelSize(R.dimen.standard_double_margin) }
|
||||
private val syncedFoldersTitleMargin
|
||||
by lazy { context.resources.getDimensionPixelSize(R.dimen.synced_folders_title_margin) }
|
||||
|
||||
init {
|
||||
shouldShowHeadersForEmptySections(true)
|
||||
shouldShowFooters(true)
|
||||
@@ -237,58 +250,112 @@ class SyncedFolderAdapter(
|
||||
return -1
|
||||
}
|
||||
|
||||
@Suppress("NestedBlockDepth")
|
||||
override fun onBindHeaderViewHolder(commonHolder: SectionedViewHolder, section: Int, expanded: Boolean) {
|
||||
if (section < filteredSyncFolderItems.size) {
|
||||
val holder = commonHolder as HeaderViewHolder
|
||||
holder.binding.headerContainer.visibility = View.VISIBLE
|
||||
|
||||
if (section == 0) {
|
||||
holder.binding.autoUploadBatterySaverWarningCard.root.run {
|
||||
setVisibleIf(powerManagementService.isPowerSavingEnabled)
|
||||
viewThemeUtils.material.themeCardView(this)
|
||||
holder.binding.run {
|
||||
headerContainer.visibility = View.VISIBLE
|
||||
|
||||
if (section == 0) {
|
||||
autoUploadBatterySaverWarningCard.root.run {
|
||||
setVisibleIf(powerManagementService.isPowerSavingEnabled)
|
||||
viewThemeUtils.material.themeCardView(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
holder.binding.title.text = filteredSyncFolderItems[section].folderName
|
||||
val syncedFolder = filteredSyncFolderItems[section]
|
||||
|
||||
if (MediaFolderType.VIDEO == filteredSyncFolderItems[section].type) {
|
||||
holder.binding.type.setImageResource(R.drawable.video_32dp)
|
||||
} else if (MediaFolderType.IMAGE == filteredSyncFolderItems[section].type) {
|
||||
holder.binding.type.setImageResource(R.drawable.image_32dp)
|
||||
} else {
|
||||
holder.binding.type.setImageResource(R.drawable.folder_star_32dp)
|
||||
}
|
||||
title.text = syncedFolder.folderName
|
||||
|
||||
holder.binding.syncStatusButton.visibility = View.VISIBLE
|
||||
holder.binding.syncStatusButton.tag = section
|
||||
holder.binding.syncStatusButton.setOnClickListener {
|
||||
filteredSyncFolderItems[section].setEnabled(
|
||||
!filteredSyncFolderItems[section].isEnabled,
|
||||
clock.currentTime
|
||||
)
|
||||
setSyncButtonActiveIcon(
|
||||
holder.binding.syncStatusButton,
|
||||
filteredSyncFolderItems[section].isEnabled
|
||||
)
|
||||
clickListener.onSyncStatusToggleClick(section, filteredSyncFolderItems[section])
|
||||
}
|
||||
setSyncButtonActiveIcon(holder.binding.syncStatusButton, filteredSyncFolderItems[section].isEnabled)
|
||||
if (MediaFolderType.VIDEO == syncedFolder.type) {
|
||||
type.setImageResource(R.drawable.video_32dp)
|
||||
} else if (MediaFolderType.IMAGE == syncedFolder.type) {
|
||||
type.setImageResource(R.drawable.image_32dp)
|
||||
} else {
|
||||
type.setImageResource(R.drawable.folder_star_32dp)
|
||||
}
|
||||
|
||||
if (light) {
|
||||
holder.binding.settingsButton.visibility = View.GONE
|
||||
} else {
|
||||
holder.binding.settingsButton.visibility = View.VISIBLE
|
||||
holder.binding.settingsButton.tag = section
|
||||
holder.binding.settingsButton.setOnClickListener { v: View ->
|
||||
onOverflowIconClicked(
|
||||
section,
|
||||
filteredSyncFolderItems[section],
|
||||
v
|
||||
syncStatusButton.visibility = View.VISIBLE
|
||||
syncStatusButton.tag = section
|
||||
syncStatusButton.setOnClickListener {
|
||||
syncedFolder.setEnabled(
|
||||
!syncedFolder.isEnabled,
|
||||
clock.currentTime
|
||||
)
|
||||
setSyncButtonActiveIcon(
|
||||
syncStatusButton,
|
||||
syncedFolder.isEnabled
|
||||
)
|
||||
clickListener.onSyncStatusToggleClick(section, syncedFolder)
|
||||
}
|
||||
}
|
||||
setSyncButtonActiveIcon(syncStatusButton, syncedFolder.isEnabled)
|
||||
|
||||
initSubFolderWarningButton(holder, section)
|
||||
if (light) {
|
||||
settingsButton.visibility = View.GONE
|
||||
} else {
|
||||
settingsButton.visibility = View.VISIBLE
|
||||
settingsButton.tag = section
|
||||
settingsButton.setOnClickListener { v: View ->
|
||||
onOverflowIconClicked(
|
||||
section,
|
||||
syncedFolder,
|
||||
v
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
initSubFolderWarningButton(holder, section)
|
||||
initNextScanIndicator(holder, syncedFolder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initNextScanIndicator(holder: HeaderViewHolder, syncedFolder: SyncedFolder) {
|
||||
val scanIndicatorText = getNextScanIndicatorText(syncedFolder)
|
||||
|
||||
holder.binding.scanIndicatorText.setVisibleIf(syncedFolder.isEnabled && (scanIndicatorText != null))
|
||||
|
||||
if (holder.binding.scanIndicatorText.isVisible) {
|
||||
setMaxWidthOfScanIndicatorText(holder)
|
||||
holder.binding.scanIndicatorText.text = scanIndicatorText
|
||||
} else {
|
||||
setBottomMarginOfTitle(holder)
|
||||
}
|
||||
}
|
||||
|
||||
private fun setMaxWidthOfScanIndicatorText(holder: HeaderViewHolder) {
|
||||
var visibleTrailingIconCount = 2
|
||||
if (holder.binding.subFolderWarningButton.isVisible) {
|
||||
visibleTrailingIconCount += 1
|
||||
}
|
||||
|
||||
val takenTrailingSpace = minimumSizeForTouchableArea * visibleTrailingIconCount
|
||||
val maxWidthInPxOfScanIndicatorText = (screenWidth - takenTrailingSpace) - standardDoubleMargin
|
||||
|
||||
holder.binding.scanIndicatorText.maxWidth = maxWidthInPxOfScanIndicatorText
|
||||
}
|
||||
|
||||
private fun setBottomMarginOfTitle(holder: HeaderViewHolder) {
|
||||
val layoutParams = holder.binding.title.layoutParams as ViewGroup.MarginLayoutParams
|
||||
layoutParams.bottomMargin = syncedFoldersTitleMargin
|
||||
holder.binding.title.layoutParams = layoutParams
|
||||
}
|
||||
|
||||
private fun getNextScanIndicatorText(syncedFolder: SyncedFolder): String? {
|
||||
val scanInterval = syncedFolder.calculateScanInterval(connectivityService, powerManagementService)
|
||||
val nextScanInMillis = scanInterval.first - System.currentTimeMillis()
|
||||
val minutesLeft = TimeUnit.MILLISECONDS
|
||||
.toMinutes(nextScanInMillis)
|
||||
.coerceAtLeast(0)
|
||||
.toInt()
|
||||
|
||||
return if (minutesLeft <= 0) {
|
||||
null
|
||||
} else {
|
||||
val scanIntervalMessageId = scanInterval.second ?: return null
|
||||
context.getString(scanIntervalMessageId)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.adapter;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.NotificationManager;
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Context;
|
||||
@@ -59,6 +60,7 @@ import com.owncloud.android.utils.theme.ViewThemeUtils;
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
@@ -67,6 +69,7 @@ import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import kotlin.Unit;
|
||||
|
||||
/**
|
||||
* This Adapter populates a ListView with following types of uploads: pending, active, completed. Filtering possible.
|
||||
@@ -74,6 +77,18 @@ import androidx.annotation.NonNull;
|
||||
public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedViewHolder> {
|
||||
private static final String TAG = UploadListAdapter.class.getSimpleName();
|
||||
|
||||
private static class GroupConfig {
|
||||
final Type type;
|
||||
final int titleRes;
|
||||
final UploadStatus status;
|
||||
|
||||
GroupConfig(Type type, int titleRes, UploadStatus status) {
|
||||
this.type = type;
|
||||
this.titleRes = titleRes;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
private UploadProgressListener uploadProgressListener;
|
||||
private final FileActivity parentActivity;
|
||||
private final UploadsStorageManager uploadsStorageManager;
|
||||
@@ -93,6 +108,66 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
|
||||
private final FileUploadHelper uploadHelper = FileUploadHelper.Companion.instance();
|
||||
|
||||
public UploadListAdapter(final FileActivity fileActivity,
|
||||
final UploadsStorageManager uploadsStorageManager,
|
||||
final FileDataStorageManager storageManager,
|
||||
final UserAccountManager accountManager,
|
||||
final ConnectivityService connectivityService,
|
||||
final PowerManagementService powerManagementService,
|
||||
final Clock clock,
|
||||
final ViewThemeUtils viewThemeUtils) {
|
||||
Log_OC.d(TAG, "UploadListAdapter");
|
||||
|
||||
this.parentActivity = fileActivity;
|
||||
this.uploadsStorageManager = uploadsStorageManager;
|
||||
this.storageManager = storageManager;
|
||||
this.accountManager = accountManager;
|
||||
this.connectivityService = connectivityService;
|
||||
this.powerManagementService = powerManagementService;
|
||||
this.clock = clock;
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
|
||||
uploadGroups = new UploadGroup[4];
|
||||
|
||||
shouldShowHeadersForEmptySections(false);
|
||||
initUploadGroups();
|
||||
showUser = accountManager.getAccounts().length > 1;
|
||||
}
|
||||
|
||||
private void initUploadGroups() {
|
||||
final var optionalUser = parentActivity.getUser();
|
||||
if (optionalUser.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final var accountName = optionalUser.get().getAccountName();
|
||||
|
||||
var groups = List.of(
|
||||
new GroupConfig(Type.CURRENT, R.string.uploads_view_group_current_uploads, UploadStatus.UPLOAD_IN_PROGRESS),
|
||||
new GroupConfig(Type.FAILED, R.string.uploads_view_group_failed_uploads, UploadStatus.UPLOAD_FAILED),
|
||||
new GroupConfig(Type.CANCELLED, R.string.uploads_view_group_manually_cancelled_uploads, UploadStatus.UPLOAD_CANCELLED),
|
||||
new GroupConfig(Type.FINISHED, R.string.uploads_view_group_finished_uploads, UploadStatus.UPLOAD_SUCCEEDED)
|
||||
);
|
||||
|
||||
for (int i = 0; i < groups.size(); i++) {
|
||||
var config = groups.get(i);
|
||||
uploadGroups[i] = createUploadGroup(config, accountName);
|
||||
}
|
||||
}
|
||||
|
||||
private UploadGroup createUploadGroup(GroupConfig config, String accountName) {
|
||||
return new UploadGroup(config.type, parentActivity.getString(config.titleRes)) {
|
||||
@Override
|
||||
public void refresh(LoadCompleteListener listener) {
|
||||
uploadHelper.getUploadsByStatus(accountName, config.status, ocUploads -> {
|
||||
fixAndSortItems(ocUploads);
|
||||
listener.onComplete();
|
||||
return Unit.INSTANCE;
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSectionCount() {
|
||||
return uploadGroups.length;
|
||||
@@ -144,7 +219,10 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
return;
|
||||
}
|
||||
|
||||
uploadHelper.cancelFileUploads(Arrays.asList(group.items), accountName);
|
||||
for (OCUpload upload: group.items) {
|
||||
uploadHelper.updateUploadStatus(upload.getRemotePath(), accountName, UploadStatus.UPLOAD_CANCELLED);
|
||||
FileUploadWorker.Companion.cancelCurrentUpload(upload.getRemotePath(), accountName, () -> Unit.INSTANCE);
|
||||
}
|
||||
loadUploadItemsFromDb();
|
||||
}).start();
|
||||
case FINISHED -> {
|
||||
@@ -242,66 +320,6 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
// not needed
|
||||
}
|
||||
|
||||
public UploadListAdapter(final FileActivity fileActivity,
|
||||
final UploadsStorageManager uploadsStorageManager,
|
||||
final FileDataStorageManager storageManager,
|
||||
final UserAccountManager accountManager,
|
||||
final ConnectivityService connectivityService,
|
||||
final PowerManagementService powerManagementService,
|
||||
final Clock clock,
|
||||
final ViewThemeUtils viewThemeUtils) {
|
||||
Log_OC.d(TAG, "UploadListAdapter");
|
||||
|
||||
this.parentActivity = fileActivity;
|
||||
this.uploadsStorageManager = uploadsStorageManager;
|
||||
this.storageManager = storageManager;
|
||||
this.accountManager = accountManager;
|
||||
this.connectivityService = connectivityService;
|
||||
this.powerManagementService = powerManagementService;
|
||||
this.clock = clock;
|
||||
this.viewThemeUtils = viewThemeUtils;
|
||||
|
||||
uploadGroups = new UploadGroup[4];
|
||||
|
||||
shouldShowHeadersForEmptySections(false);
|
||||
|
||||
uploadGroups[0] = new UploadGroup(Type.CURRENT,
|
||||
parentActivity.getString(R.string.uploads_view_group_current_uploads)) {
|
||||
@Override
|
||||
public void refresh() {
|
||||
fixAndSortItems(uploadsStorageManager.getCurrentAndPendingUploadsForCurrentAccount());
|
||||
}
|
||||
};
|
||||
|
||||
uploadGroups[1] = new UploadGroup(Type.FAILED,
|
||||
parentActivity.getString(R.string.uploads_view_group_failed_uploads)) {
|
||||
@Override
|
||||
public void refresh() {
|
||||
fixAndSortItems(uploadsStorageManager.getFailedButNotDelayedUploadsForCurrentAccount());
|
||||
}
|
||||
};
|
||||
|
||||
uploadGroups[2] = new UploadGroup(Type.CANCELLED,
|
||||
parentActivity.getString(
|
||||
R.string.uploads_view_group_manually_cancelled_uploads)) {
|
||||
@Override
|
||||
public void refresh() {
|
||||
fixAndSortItems(uploadsStorageManager.getCancelledUploadsForCurrentAccount());
|
||||
}
|
||||
};
|
||||
|
||||
uploadGroups[3] = new UploadGroup(Type.FINISHED,
|
||||
parentActivity.getString(R.string.uploads_view_group_finished_uploads)) {
|
||||
@Override
|
||||
public void refresh() {
|
||||
fixAndSortItems(uploadsStorageManager.getFinishedUploadsForCurrentAccount());
|
||||
}
|
||||
};
|
||||
|
||||
showUser = accountManager.getAccounts().length > 1;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(SectionedViewHolder holder, int section, int relativePosition, int absolutePosition) {
|
||||
if (uploadGroups.length == 0 || section < 0 || section >= uploadGroups.length) {
|
||||
@@ -427,7 +445,8 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
itemViewHolder.binding.uploadRightButton.setImageResource(R.drawable.ic_action_cancel_grey);
|
||||
itemViewHolder.binding.uploadRightButton.setVisibility(View.VISIBLE);
|
||||
itemViewHolder.binding.uploadRightButton.setOnClickListener(v -> {
|
||||
uploadHelper.cancelFileUpload(item.getRemotePath(), item.getAccountName());
|
||||
uploadHelper.updateUploadStatus(item.getRemotePath(), item.getAccountName(), UploadStatus.UPLOAD_CANCELLED);
|
||||
FileUploadWorker.Companion.cancelCurrentUpload(item.getRemotePath(), item.getAccountName(), () -> Unit.INSTANCE);
|
||||
loadUploadItemsFromDb();
|
||||
});
|
||||
|
||||
@@ -914,7 +933,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
}
|
||||
|
||||
interface Refresh {
|
||||
void refresh();
|
||||
void refresh(LoadCompleteListener listener);
|
||||
}
|
||||
|
||||
interface Apply {
|
||||
@@ -993,20 +1012,30 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@Override
|
||||
public void run() {
|
||||
final int groupCount = uploadGroups.length;
|
||||
final int[] completedCount = {0};
|
||||
|
||||
for (UploadGroup group : uploadGroups) {
|
||||
group.refresh();
|
||||
group.refresh(() -> {
|
||||
synchronized (completedCount) {
|
||||
group.apply();
|
||||
completedCount[0]++;
|
||||
if (completedCount[0] == groupCount) {
|
||||
|
||||
// All groups finished, update UI once
|
||||
parentActivity.runOnUiThread(() -> {
|
||||
notifyDataSetChanged();
|
||||
for (LoadCompleteListener loadCompleteListener : loadCompleteListenerSet) {
|
||||
loadCompleteListener.onComplete();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
parentActivity.runOnUiThread(() -> {
|
||||
for (UploadGroup uploadGroup : uploadGroups) {
|
||||
uploadGroup.apply();
|
||||
}
|
||||
notifyDataSetChanged();
|
||||
for (LoadCompleteListener loadCompleteListener : loadCompleteListenerSet) {
|
||||
loadCompleteListener.onComplete();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Objects;
|
||||
|
||||
import static android.content.Context.PRINT_SERVICE;
|
||||
|
||||
@@ -56,69 +58,67 @@ public class PrintAsyncTask extends AsyncTask<Void, Void, Boolean> {
|
||||
|
||||
@Override
|
||||
protected Boolean doInBackground(Void... voids) {
|
||||
if (file == null) return Boolean.FALSE;
|
||||
|
||||
HttpClient client = new HttpClient();
|
||||
GetMethod getMethod = null;
|
||||
|
||||
FileOutputStream fos = null;
|
||||
try {
|
||||
getMethod = new GetMethod(url);
|
||||
int status = client.executeMethod(getMethod);
|
||||
if (status == HttpStatus.SC_OK) {
|
||||
if (file.exists() && !file.delete()) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (status != HttpStatus.SC_OK) return Boolean.FALSE;
|
||||
|
||||
file.getParentFile().mkdirs();
|
||||
if (file.exists() && !file.delete()) return Boolean.FALSE;
|
||||
|
||||
if (!file.getParentFile().exists()) {
|
||||
Log_OC.d(TAG, file.getParentFile().getAbsolutePath() + " does not exist");
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
File parentFile = file.getParentFile();
|
||||
if (parentFile == null) return Boolean.FALSE;
|
||||
|
||||
if (!file.createNewFile()) {
|
||||
Log_OC.d(TAG, file.getAbsolutePath() + " could not be created");
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
Files.createDirectories(parentFile.toPath());
|
||||
if (!parentFile.exists()) {
|
||||
Log_OC.d(TAG, parentFile.getAbsolutePath() + " does not exist");
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
if (!file.createNewFile()) {
|
||||
Log_OC.d(TAG, file.getAbsolutePath() + " could not be created");
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
|
||||
long totalToTransfer = 0;
|
||||
if (contentLengthHeader != null && !contentLengthHeader.getValue().isEmpty()) {
|
||||
totalToTransfer = Long.parseLong(contentLengthHeader.getValue());
|
||||
}
|
||||
|
||||
try (
|
||||
BufferedInputStream bis = new BufferedInputStream(getMethod.getResponseBodyAsStream());
|
||||
fos = new FileOutputStream(file);
|
||||
FileOutputStream fos = new FileOutputStream(file)
|
||||
) {
|
||||
byte[] buffer = new byte[4096];
|
||||
long transferred = 0;
|
||||
int read;
|
||||
|
||||
Header contentLength = getMethod.getResponseHeader("Content-Length");
|
||||
long totalToTransfer = contentLength != null && contentLength.getValue().length() > 0 ?
|
||||
Long.parseLong(contentLength.getValue()) : 0;
|
||||
|
||||
byte[] bytes = new byte[4096];
|
||||
int readResult;
|
||||
while ((readResult = bis.read(bytes)) != -1) {
|
||||
fos.write(bytes, 0, readResult);
|
||||
transferred += readResult;
|
||||
while ((read = bis.read(buffer)) != -1) {
|
||||
fos.write(buffer, 0, read);
|
||||
transferred += read;
|
||||
}
|
||||
// Check if the file is completed
|
||||
if (transferred != totalToTransfer) {
|
||||
|
||||
if (totalToTransfer > 0 && transferred != totalToTransfer) {
|
||||
Log_OC.d(TAG, "Transferred bytes (" + transferred +
|
||||
") != expected (" + totalToTransfer + ")");
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
if (getMethod.getResponseBodyAsStream() != null) {
|
||||
getMethod.getResponseBodyAsStream().close();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
Log_OC.e(TAG, "Error reading file", e);
|
||||
|
||||
return Boolean.TRUE;
|
||||
} catch (Exception e) {
|
||||
Log_OC.e(TAG, "Error downloading file", e);
|
||||
return Boolean.FALSE;
|
||||
} finally {
|
||||
if (getMethod != null) {
|
||||
getMethod.releaseConnection();
|
||||
}
|
||||
if (fos != null) {
|
||||
try {
|
||||
fos.close();
|
||||
} catch (IOException e) {
|
||||
Log_OC.e(TAG, "Error closing file output stream", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -24,7 +24,6 @@ import com.owncloud.android.datamodel.OCFile
|
||||
import com.owncloud.android.ui.activity.FileActivity
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.dialog.ConfirmationDialogFragment.ConfirmationDialogFragmentListener
|
||||
import com.owncloud.android.ui.preview.PreviewImageActivity
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
@@ -125,14 +124,11 @@ class RemoveFilesDialogFragment :
|
||||
}
|
||||
|
||||
finishActionMode()
|
||||
finishPreviewImageActivity()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNeutral(callerTag: String?) = Unit
|
||||
|
||||
private fun finishPreviewImageActivity() = getTypedActivity(PreviewImageActivity::class.java)?.finish()
|
||||
|
||||
private fun setActionMode(actionMode: ActionMode?) {
|
||||
this.actionMode = actionMode
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.Parcelable
|
||||
import android.util.DisplayMetrics
|
||||
import android.view.KeyEvent
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MenuInflater
|
||||
@@ -57,7 +56,6 @@ import com.nextcloud.client.di.Injectable
|
||||
import com.nextcloud.client.preferences.AppPreferences
|
||||
import com.nextcloud.client.preferences.AppPreferencesImpl
|
||||
import com.nextcloud.utils.extensions.getTypedActivity
|
||||
import com.nextcloud.utils.extensions.handleBackButtonEvent
|
||||
import com.owncloud.android.MainApp
|
||||
import com.owncloud.android.R
|
||||
import com.owncloud.android.databinding.ListFragmentBinding
|
||||
@@ -65,7 +63,6 @@ import com.owncloud.android.lib.common.utils.Log_OC
|
||||
import com.owncloud.android.lib.resources.files.SearchRemoteOperation
|
||||
import com.owncloud.android.lib.resources.status.OwnCloudVersion
|
||||
import com.owncloud.android.ui.EmptyRecyclerView
|
||||
import com.owncloud.android.ui.activity.FileActivity
|
||||
import com.owncloud.android.ui.activity.FileDisplayActivity
|
||||
import com.owncloud.android.ui.activity.FolderPickerActivity
|
||||
import com.owncloud.android.ui.activity.OnEnforceableRefreshListener
|
||||
@@ -767,18 +764,7 @@ open class ExtendedListFragment :
|
||||
}
|
||||
}
|
||||
|
||||
protected fun setupBackButtonRedirectToAllFiles() {
|
||||
view?.isFocusableInTouchMode = true
|
||||
view?.requestFocus()
|
||||
view?.setOnKeyListener { _: View, keyCode: Int, event: KeyEvent ->
|
||||
if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
|
||||
val fda = getTypedActivity(FileActivity::class.java)
|
||||
val currentDir = fda?.currentDir ?: return@setOnKeyListener false
|
||||
return@setOnKeyListener fda.handleBackButtonEvent(currentDir)
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
protected fun isAccountManagerInitialized(): Boolean = ::accountManager.isInitialized
|
||||
|
||||
private data class EmptyListData(val headline: Int, val message: Int, val icon: Int?, val tintIcon: Boolean)
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ public class FileDetailFragment extends FileFragment implements OnClickListener,
|
||||
}
|
||||
|
||||
public void goBackToOCFileListFragment() {
|
||||
requireActivity().onBackPressed();
|
||||
requireActivity().getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -574,7 +574,7 @@ public class FileDetailFragment extends FileFragment implements OnClickListener,
|
||||
// configure UI for depending upon local state of the file
|
||||
if (transferring
|
||||
|| (FileDownloadHelper.Companion.instance().isDownloading(user, file))
|
||||
|| (FileUploadHelper.Companion.instance().isUploading(user, file))) {
|
||||
|| (FileUploadHelper.Companion.instance().isUploading(file.getRemotePath(), user.getAccountName()))) {
|
||||
setButtonsForTransferring();
|
||||
|
||||
} else if (file.isDown()) {
|
||||
@@ -736,7 +736,7 @@ public class FileDetailFragment extends FileFragment implements OnClickListener,
|
||||
if (FileDownloadHelper.Companion.instance().isDownloading(user, getFile())) {
|
||||
binding.progressText.setText(R.string.downloader_download_in_progress_ticker);
|
||||
} else {
|
||||
if (FileUploadHelper.Companion.instance().isUploading(user, getFile())) {
|
||||
if (FileUploadHelper.Companion.instance().isUploading(getFile().getRemotePath(), user.getAccountName())) {
|
||||
binding.progressText.setText(R.string.uploader_upload_in_progress_ticker);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,12 +234,6 @@ public class GalleryFragment extends OCFileListFragment implements GalleryFragme
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
setupBackButtonRedirectToAllFiles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageEvent(ChangeMenuEvent changeMenuEvent) {
|
||||
super.onMessageEvent(changeMenuEvent);
|
||||
|
||||
@@ -112,7 +112,6 @@ public class LocalFileListFragment extends ExtendedListFragment implements
|
||||
super.onActivityCreated(savedInstanceState);
|
||||
|
||||
mAdapter = new LocalFileListAdapter(mContainerActivity.isFolderPickerMode(),
|
||||
mContainerActivity.getInitialDirectory(),
|
||||
this,
|
||||
preferences,
|
||||
getActivity(),
|
||||
@@ -256,32 +255,30 @@ public class LocalFileListFragment extends ExtendedListFragment implements
|
||||
* @param directory Directory to be listed
|
||||
*/
|
||||
public void listDirectory(File directory) {
|
||||
|
||||
// Check input parameters for null
|
||||
if (directory == null) {
|
||||
if (mDirectory != null) {
|
||||
directory = mDirectory;
|
||||
} else {
|
||||
directory = Environment.getExternalStorageDirectory();
|
||||
// TODO be careful with the state of the storage; could not be available
|
||||
if (directory == null) {
|
||||
return; // no files to show
|
||||
}
|
||||
}
|
||||
directory = (mDirectory != null) ? mDirectory : Environment.getExternalStorageDirectory();
|
||||
if (directory == null) return;
|
||||
}
|
||||
|
||||
|
||||
// if that's not a directory -> List its parent
|
||||
// If input is not a directory, list its parent
|
||||
if (!directory.isDirectory()) {
|
||||
Log_OC.w(TAG, "You see, that is not a directory -> " + directory);
|
||||
directory = directory.getParentFile();
|
||||
if (directory == null) {
|
||||
Log_OC.w(TAG, "parent directory is null, cannot swap directory");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// by now, only files in the same directory will be kept as selected
|
||||
mAdapter.removeAllFilesFromCheckedFiles();
|
||||
mAdapter.swapDirectory(directory);
|
||||
|
||||
mDirectory = directory;
|
||||
|
||||
final var recyclerView = getRecyclerView();
|
||||
if (recyclerView != null) {
|
||||
recyclerView.scrollToPosition(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -77,6 +77,8 @@ class OCFileListBottomSheetDialog(
|
||||
colorImageView(menuIconScanDocUpload, ColorRole.PRIMARY)
|
||||
colorImageView(menuIconMkdir, ColorRole.PRIMARY)
|
||||
colorImageView(menuIconAddFolderInfo, ColorRole.PRIMARY)
|
||||
|
||||
colorViewBackground(binding.bottomSheet, ColorRole.SURFACE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,12 +277,6 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
super.onResume();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
setupBackButtonRedirectToAllFiles();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroyView() {
|
||||
super.onDestroyView();
|
||||
@@ -1247,6 +1241,11 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
}
|
||||
|
||||
private void handlePendingDownloadFile(OCFile file) {
|
||||
if (!isAccountManagerInitialized()) {
|
||||
Log_OC.e(TAG, "AccountManager not yet initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
User account = accountManager.getUser();
|
||||
OCCapability capability = mContainerActivity.getStorageManager().getCapability(account.getAccountName());
|
||||
|
||||
@@ -2325,4 +2324,15 @@ public class OCFileListFragment extends ExtendedListFragment implements
|
||||
public SearchEvent getSearchEvent() {
|
||||
return searchEvent;
|
||||
}
|
||||
|
||||
public boolean isSearchEventFavorite() {
|
||||
if (searchEvent == null) {
|
||||
return false;
|
||||
}
|
||||
return searchEvent.getSearchType() == SearchRemoteOperation.SearchType.FAVORITE_SEARCH;
|
||||
}
|
||||
|
||||
public boolean shouldNavigateBackToAllFiles() {
|
||||
return ((this instanceof GalleryFragment) || isSearchEventFavorite() || DrawerActivity.menuItemId == R.id.nav_favorites);
|
||||
}
|
||||
}
|
||||
@@ -445,7 +445,9 @@ class UnifiedSearchFragment :
|
||||
|
||||
private fun searchInCurrentDirectory(query: String) {
|
||||
currentDir?.run {
|
||||
val files = storageManager.searchFilesByName(this, accountManager.user.accountName, query)
|
||||
val files = storageManager
|
||||
.searchFilesByName(this, accountManager.user.accountName, query)
|
||||
.filter { !it.isEncrypted }
|
||||
adapter.setDataCurrentDirItems(files)
|
||||
}
|
||||
}
|
||||
@@ -462,6 +464,6 @@ class UnifiedSearchFragment :
|
||||
|
||||
override fun openFile(remotePath: String, showMoreActions: Boolean) {
|
||||
this.showMoreActions = showMoreActions
|
||||
vm.openFile(remotePath)
|
||||
vm.getRemoteFile(remotePath)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -404,7 +404,7 @@ public class BackupListFragment extends FileFragment implements Injectable {
|
||||
private void closeFragment() {
|
||||
ContactsPreferenceActivity contactsPreferenceActivity = (ContactsPreferenceActivity) getActivity();
|
||||
if (contactsPreferenceActivity != null) {
|
||||
contactsPreferenceActivity.onBackPressed();
|
||||
contactsPreferenceActivity.getOnBackPressedDispatcher().onBackPressed();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ import com.nextcloud.client.account.User;
|
||||
import com.nextcloud.client.jobs.BackgroundJobManager;
|
||||
import com.nextcloud.client.jobs.download.FileDownloadHelper;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadHelper;
|
||||
import com.nextcloud.client.jobs.upload.FileUploadWorker;
|
||||
import com.nextcloud.client.network.ConnectivityService;
|
||||
import com.nextcloud.utils.EditorUtils;
|
||||
import com.owncloud.android.MainApp;
|
||||
@@ -42,6 +43,7 @@ import com.owncloud.android.datamodel.ArbitraryDataProvider;
|
||||
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl;
|
||||
import com.owncloud.android.datamodel.FileDataStorageManager;
|
||||
import com.owncloud.android.datamodel.OCFile;
|
||||
import com.owncloud.android.datamodel.UploadsStorageManager;
|
||||
import com.owncloud.android.files.StreamMediaFileOperation;
|
||||
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
|
||||
import com.owncloud.android.lib.common.utils.Log_OC;
|
||||
@@ -86,7 +88,6 @@ import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
@@ -97,6 +98,7 @@ import androidx.annotation.Nullable;
|
||||
import androidx.core.content.FileProvider;
|
||||
import androidx.fragment.app.FragmentManager;
|
||||
import androidx.fragment.app.FragmentTransaction;
|
||||
import kotlin.Unit;
|
||||
|
||||
/**
|
||||
* Helper implementation for file operations locally and remote.
|
||||
@@ -1006,17 +1008,22 @@ public class FileOperationsHelper {
|
||||
}
|
||||
}
|
||||
|
||||
if (FileDownloadHelper.Companion.instance().isDownloading(currentUser, file)) {
|
||||
final var fileDownloadHelper = FileDownloadHelper.Companion.instance();
|
||||
if (fileDownloadHelper.isDownloading(currentUser, file)) {
|
||||
List<OCFile> files = fileActivity.getStorageManager().getAllFilesRecursivelyInsideFolder(file);
|
||||
FileDownloadHelper.Companion.instance().cancelPendingOrCurrentDownloads(currentUser, files);
|
||||
fileDownloadHelper.cancelPendingOrCurrentDownloads(currentUser, files);
|
||||
}
|
||||
|
||||
if (FileUploadHelper.Companion.instance().isUploading(currentUser, file)) {
|
||||
try {
|
||||
FileUploadHelper.Companion.instance().cancelFileUpload(file.getRemotePath(), currentUser.getAccountName());
|
||||
} catch (NoSuchElementException e) {
|
||||
Log_OC.e(TAG, "Error cancelling current upload because user does not exist!");
|
||||
}
|
||||
if (file.isFolder()) {
|
||||
fileDownloadHelper.cancelFolderDownload();
|
||||
}
|
||||
|
||||
final var fileUploadHelper = FileUploadHelper.Companion.instance();
|
||||
if (fileUploadHelper.isUploading(file.getRemotePath(), currentUser.getAccountName())) {
|
||||
FileUploadWorker.Companion.cancelCurrentUpload(file.getRemotePath(), currentUser.getAccountName(), () -> {
|
||||
fileUploadHelper.updateUploadStatus(file.getRemotePath(), currentUser.getAccountName(), UploadsStorageManager.UploadStatus.UPLOAD_CANCELLED);
|
||||
return Unit.INSTANCE;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ object NotificationUtils {
|
||||
const val NOTIFICATION_CHANNEL_PUSH: String = "NOTIFICATION_CHANNEL_PUSH"
|
||||
const val NOTIFICATION_CHANNEL_BACKGROUND_OPERATIONS: String = "NOTIFICATION_CHANNEL_BACKGROUND_OPERATIONS"
|
||||
const val NOTIFICATION_CHANNEL_OFFLINE_OPERATIONS: String = "NOTIFICATION_CHANNEL_OFFLINE_OPERATIONS"
|
||||
const val NOTIFICATION_CHANNEL_CONTENT_OBSERVER: String = "NOTIFICATION_CHANNEL_CONTENT_OBSERVER"
|
||||
|
||||
fun createUploadNotificationTag(file: OCFile): String =
|
||||
createUploadNotificationTag(file.remotePath, file.storagePath)
|
||||
|
||||
@@ -54,7 +54,7 @@ class PreviewBitmapActivity :
|
||||
}
|
||||
|
||||
override fun onSupportNavigateUp(): Boolean {
|
||||
onBackPressed()
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.view.MenuItem
|
||||
import android.view.View
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.appcompat.app.ActionBar
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.drawerlayout.widget.DrawerLayout
|
||||
@@ -55,6 +56,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
|
||||
import java.io.Serializable
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Holds a swiping gallery where image files contained in an Nextcloud directory are shown.
|
||||
@@ -123,6 +125,7 @@ class PreviewImageActivity :
|
||||
|
||||
observeWorkerState()
|
||||
applyDisplayCutOutTopPadding()
|
||||
handleBackPress()
|
||||
}
|
||||
|
||||
private fun applyDisplayCutOutTopPadding() {
|
||||
@@ -214,9 +217,25 @@ class PreviewImageActivity :
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBackPressed() {
|
||||
sendRefreshSearchEventBroadcast()
|
||||
super.onBackPressed()
|
||||
private fun updateViewPagerAfterDeletionAndAdvanceForward() {
|
||||
val deletePosition = viewPager?.currentItem ?: return
|
||||
previewImagePagerAdapter?.let { adapter ->
|
||||
val nextPosition = min(deletePosition, adapter.itemCount - 1)
|
||||
viewPager?.setCurrentItem(nextPosition, true)
|
||||
adapter.delete(deletePosition)
|
||||
// Page needs to be reselected after the adapter has been updated. Otherwise, wrong title is shown
|
||||
selectPage(nextPosition)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleBackPress() {
|
||||
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
sendRefreshSearchEventBroadcast()
|
||||
isEnabled = false
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
override fun onOptionsItemSelected(item: MenuItem): Boolean {
|
||||
@@ -278,9 +297,6 @@ class PreviewImageActivity :
|
||||
super.onRemoteOperationFinish(operation, result)
|
||||
|
||||
if (operation is RemoveFileOperation) {
|
||||
val deletePosition = viewPager?.currentItem ?: return
|
||||
val nextPosition = if (deletePosition > 0) deletePosition - 1 else 0
|
||||
|
||||
previewImagePagerAdapter?.let {
|
||||
if (it.itemCount <= 1) {
|
||||
backToDisplayActivity()
|
||||
@@ -288,12 +304,9 @@ class PreviewImageActivity :
|
||||
}
|
||||
}
|
||||
|
||||
if (user.isPresent) {
|
||||
initViewPager(user.get())
|
||||
if (result.isSuccess) {
|
||||
updateViewPagerAfterDeletionAndAdvanceForward()
|
||||
}
|
||||
|
||||
viewPager?.setCurrentItem(nextPosition, true)
|
||||
previewImagePagerAdapter?.delete(deletePosition)
|
||||
} else if (operation is SynchronizeFileOperation) {
|
||||
onSynchronizeFileOperationFinish(result)
|
||||
}
|
||||
|
||||
@@ -63,7 +63,9 @@ class PreviewImagePagerAdapter : FragmentStateAdapter {
|
||||
imageFiles = mStorageManager.getFolderImages(parentFolder, onlyOnDevice)
|
||||
|
||||
val sortOrder = preferences.getSortOrderByFolder(parentFolder)
|
||||
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList()).toMutableList()
|
||||
val foldersBeforeFiles = preferences.isSortFoldersBeforeFiles()
|
||||
val favoritesFirst = preferences.isSortFavoritesFirst()
|
||||
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList(), foldersBeforeFiles, favoritesFirst)
|
||||
|
||||
mObsoleteFragments = HashSet()
|
||||
mObsoletePositions = HashSet()
|
||||
@@ -101,7 +103,9 @@ class PreviewImagePagerAdapter : FragmentStateAdapter {
|
||||
|
||||
if (type == VirtualFolderType.FAVORITE) {
|
||||
val sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.favoritesListView)
|
||||
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList()).toMutableList()
|
||||
val foldersBeforeFiles = preferences.isSortFoldersBeforeFiles()
|
||||
val favoritesFirst = preferences.isSortFavoritesFirst()
|
||||
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList(), foldersBeforeFiles, favoritesFirst)
|
||||
}
|
||||
|
||||
mObsoleteFragments = HashSet()
|
||||
@@ -201,4 +205,11 @@ class PreviewImagePagerAdapter : FragmentStateAdapter {
|
||||
override fun createFragment(position: Int): Fragment = getItem(position)
|
||||
|
||||
override fun getItemCount(): Int = imageFiles.size
|
||||
|
||||
override fun getItemId(position: Int): Long {
|
||||
// The item ID function is needed to detect whether the deletion of the current item needs a UI update
|
||||
return imageFiles.getOrNull(position)?.fileId ?: position.toLong()
|
||||
}
|
||||
|
||||
override fun containsItem(itemId: Long): Boolean = imageFiles.any { it.fileId == itemId }
|
||||
}
|
||||
@@ -165,7 +165,7 @@ abstract class PreviewTextFragment :
|
||||
* Finishes the preview
|
||||
*/
|
||||
protected fun finish() {
|
||||
requireActivity().runOnUiThread { requireActivity().onBackPressed() }
|
||||
requireActivity().runOnUiThread { requireActivity().onBackPressedDispatcher.onBackPressed() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -7,15 +7,16 @@
|
||||
*/
|
||||
package com.owncloud.android.ui.preview
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Dialog
|
||||
import android.os.Build
|
||||
import android.view.ViewGroup
|
||||
import android.view.Window
|
||||
import androidx.activity.addCallback
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.ui.PlayerView
|
||||
@@ -35,7 +36,7 @@ import com.owncloud.android.lib.common.utils.Log_OC
|
||||
*/
|
||||
@OptIn(UnstableApi::class)
|
||||
class PreviewVideoFullscreenDialog(
|
||||
private val activity: Activity,
|
||||
private val activity: FragmentActivity,
|
||||
nextcloudClient: NextcloudClient,
|
||||
private val sourceExoPlayer: ExoPlayer,
|
||||
private val sourceView: PlayerView
|
||||
@@ -69,6 +70,7 @@ class PreviewVideoFullscreenDialog(
|
||||
binding.videoPlayer.player = mExoPlayer
|
||||
mExoPlayer.prepare()
|
||||
}
|
||||
handleOnBackPressed()
|
||||
}
|
||||
|
||||
private fun isRotatedVideo(): Boolean {
|
||||
@@ -95,7 +97,7 @@ class PreviewVideoFullscreenDialog(
|
||||
setOnShowListener {
|
||||
enableImmersiveMode()
|
||||
switchTargetViewFromSource()
|
||||
binding.videoPlayer.setFullscreenButtonClickListener { onBackPressed() }
|
||||
binding.videoPlayer.setFullscreenButtonClickListener { activity.onBackPressedDispatcher.onBackPressed() }
|
||||
if (isPlaying) {
|
||||
mExoPlayer.play()
|
||||
}
|
||||
@@ -111,23 +113,25 @@ class PreviewVideoFullscreenDialog(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBackPressed() {
|
||||
val isPlaying = mExoPlayer.isPlaying
|
||||
if (isPlaying) {
|
||||
mExoPlayer.pause()
|
||||
}
|
||||
setOnDismissListener {
|
||||
disableImmersiveMode()
|
||||
playingStateListener?.let {
|
||||
mExoPlayer.removeListener(it)
|
||||
}
|
||||
switchTargetViewToSource()
|
||||
private fun handleOnBackPressed() {
|
||||
activity.onBackPressedDispatcher.addCallback(activity) {
|
||||
val isPlaying = mExoPlayer.isPlaying
|
||||
if (isPlaying) {
|
||||
sourceExoPlayer.play()
|
||||
mExoPlayer.pause()
|
||||
}
|
||||
sourceView.showController()
|
||||
setOnDismissListener {
|
||||
disableImmersiveMode()
|
||||
playingStateListener?.let {
|
||||
mExoPlayer.removeListener(it)
|
||||
}
|
||||
switchTargetViewToSource()
|
||||
if (isPlaying) {
|
||||
sourceExoPlayer.play()
|
||||
}
|
||||
sourceView.showController()
|
||||
}
|
||||
dismiss()
|
||||
}
|
||||
dismiss()
|
||||
}
|
||||
|
||||
private fun switchTargetViewToSource() {
|
||||
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user