Compare commits

..
Author SHA1 Message Date
Alex Knop 7a8ef1fb93 rework normalUpload
Signed-off-by: Alex Knop <[email protected]>
2025-10-07 11:15:52 -04:00
Alex Knop 094adf3fa0 try with resources for RandomAccessFile and FileInputStream
Signed-off-by: Alex Knop <[email protected]>
2025-10-07 11:15:52 -04:00
232 changed files with 1970 additions and 6562 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:noble@sha256:66460d557b25769b102175144d538d88219c077c678a49af4afca6fbfc1b5252
FROM ubuntu:noble@sha256:353675e2a41babd526e2b837d7ec780c2a05bca0164f7ea5dbbd433d21d166fc
ARG DEBIAN_FRONTEND=noninteractive
ENV ANDROID_HOME=/usr/lib/android-sdk
-1
View File
@@ -27,7 +27,6 @@ concurrency:
jobs:
analysis:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Disabled on forks
if: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }}
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
with:
distribution: "temurin"
java-version: 17
- uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- uses: gradle/actions/wrapper-validation@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
- name: Build ${{ matrix.flavor }}
run: |
echo "org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" >> gradle.properties
+2 -2
View File
@@ -43,7 +43,7 @@ jobs:
with:
swap-size-gb: 10
- name: Initialize CodeQL
uses: github/codeql-action/init@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/init@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
with:
languages: ${{ matrix.language }}
- name: Set up JDK 17
@@ -57,4 +57,4 @@ jobs:
echo "org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError" > "$HOME/.gradle/gradle.properties"
./gradlew assembleDebug
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/analyze@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
+1 -1
View File
@@ -24,4 +24,4 @@ jobs:
persist-credentials: false
- name: REUSE Compliance Check
uses: fsfe/reuse-action@676e2d560c9a403aa252096d99fcab3e1132b0f5 # v6.0.0
uses: fsfe/reuse-action@bb774aa972c2a89ff34781233d275075cbddf542 # v5.0.0
+1 -1
View File
@@ -42,6 +42,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@4e94bd11f71e507f7f87df81788dff88d1dacbfb # v4.31.0
uses: github/codeql-action/upload-sarif@64d10c13136e1c5bce3e5fbde8d4906eeaafc885 # v3.30.6
with:
sarif_file: results.sarif
+1 -1
View File
@@ -102,7 +102,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: scripts/uploadReport.sh "${{ secrets.LOG_USERNAME }}" "${{ secrets.LOG_PASSWORD }}" ${{github.event.number}} "${{ matrix.color }}-${{ matrix.scheme }}" "Screenshot" ${{github.event.number}}
- name: Archive Espresso results
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
if: ${{ always() }}
with:
name: Report-${{ matrix.color }}-${{ matrix.scheme }}
+2 -2
View File
@@ -33,7 +33,7 @@ jobs:
if: ${{ always() }}
run: scripts/deleteOldComments.sh "test" "Unit" ${{github.event.number}}
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
- 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@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: test-results
path: app/build/reports/tests/testGplayDebugUnitTest/
-120
View File
@@ -1,120 +0,0 @@
<!--
~ SPDX-FileCopyrightText: 2025 Saeed <[email protected]>
~ SPDX-License-Identifier: AGPL-3.0-or-later OR GPL-2.0-only
-->
# تطبيق [Nextcloud](https://nextcloud.com)لأجهزة أندرويد 📱
[![حالة REUSE](https://api.reuse.software/badge/github.com/nextcloud/android)](https://api.reuse.software/info/github.com/nextcloud/android)
[![حالة البناء](https://drone.nextcloud.com/api/badges/nextcloud/android/status.svg)](https://drone.nextcloud.com/nextcloud/android)
[![تقييم Codacy](https://app.codacy.com/project/badge/Grade/fb4cf26336774ee3a5c9adfe829c41aa)](https://app.codacy.com/gh/nextcloud/android/dashboard)
[![الإصدارات](https://img.shields.io/github/release/nextcloud/android.svg)](https://github.com/nextcloud/android/releases/latest)
[<img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png" alt="تحميل من Google Play" height="80">](https://play.google.com/store/apps/details?id=com.nextcloud.client)
[<img src="https://f-droid.org/badge/get-it-on.png" alt="احصل عليه من F-Droid" height="80">](https://f-droid.org/packages/com.nextcloud.client/)
## التحقق من توقيع التطبيق 🔐
للتأكد من صحة ملف APK:
- ملف APK باسم "gplay" متوفر [هنا](https://github.com/nextcloud/android/releases) أو عبر متجر Google Play
- ملف APK باسم "nextcloud" متوفر [هنا](https://github.com/nextcloud/android/releases)
- غير مناسب لتحميلات F-Droid، لأن F-Droid يقوم بتوقيعه بنفسه
```plaintext
SHA-256: fb009522f65e25802261b67b10a45fd70e610031976f40b28a649e152ded0373
SHA-1: 74aa1702e714941be481e1f7ce4a8f779c19dcea
```
**تطبيق Nextcloud لأندرويد يتيح لك إدارة بياناتك بسهولة على خادم Nextcloud الخاص بك.**
## الحصول على الدعم 🆘
إذا واجهت مشكلة أو لديك سؤال، يمكنك زيارة [منتدى الدعم](https://help.nextcloud.com/c/clients/android).
إذا اكتشفت خطأ أو لديك اقتراح لتحسين التطبيق، يمكنك [فتح قضية جديدة على GitHub](https://github.com/nextcloud/android/issues).
إذا لم تكن متأكدًا ما إذا كانت المشكلة ناتجة عن التطبيق أو الإعدادات أو الخادم، فابدأ بالسؤال في المنتدى، ثم عد إلى GitHub إذا لزم الأمر.
> ملاحظة: هذا المستودع خاص بتطبيق أندرويد فقط. إذا كانت المشكلة في الخادم، يرجى التواصل مع [فريق خادم Nextcloud](https://github.com/nextcloud/server).
## كيف تساهم في المشروع 🚀
هناك العديد من الطرق للمساهمة، سواء كنت مبرمجًا أو لا:
- مساعدة المستخدمين في المنتدى: https://help.nextcloud.com
- ترجمة التطبيق عبر [Transifex](https://app.transifex.com/nextcloud/nextcloud/android/)
- الإبلاغ عن المشاكل أو تقديم اقتراحات عبر [GitHub Issues](https://github.com/nextcloud/android/issues/new/choose)
- تنفيذ إصلاحات أو تحسينات عبر Pull Requests
- مراجعة [طلبات الدمج](https://github.com/nextcloud/android/pulls)
- اختبار النسخ التجريبية أو اليومية أو المرشحة للإصدار
- تحسين [التوثيق](https://github.com/nextcloud/documentation/)
- اختبار الميزات الأساسية في آخر إصدار مستقر
- تعلم كيفية جمع سجلات الأخطاء (logcat) لتقديم تقارير دقيقة
## إرشادات المساهمة والترخيص 📜
- الترخيص: [GPLv2](https://github.com/nextcloud/android/blob/master/LICENSE.txt)
- جميع المساهمات بعد 16 يونيو 2016 تعتبر مرخصة تحت AGPLv3 أو أي إصدار لاحق
- لا حاجة لتوقيع اتفاقية مساهم (CLA)
- يُفضل إضافة السطر التالي في رأس الملف عند إجراء تغييرات كبيرة:
```plaintext
SPDX-FileCopyrightText: <السنة> <اسمك> <بريدك الإلكتروني>
```
يرجى قراءة [مدونة السلوك](https://nextcloud.com/community/code-of-conduct/) لضمان بيئة تعاون إيجابية.
راجع أيضًا [إرشادات المساهمة](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md).
## ابدأ بالمساهمة 🔧
- اقرأ [SETUP.md](https://github.com/nextcloud/android/blob/master/SETUP.md) و[CONTRIBUTING.md](https://github.com/nextcloud/android/blob/master/CONTRIBUTING.md)
- قم بعمل fork للمستودع وابدأ بإرسال Pull Requests إلى فرع master
- يمكنك البدء بمراجعة [طلبات الدمج](https://github.com/nextcloud/android/pulls) أو العمل على [القضايا المبتدئة](https://github.com/nextcloud/android/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22)
## جمع سجلات الأخطاء (logcat) 🔍
### على لينكس:
- فعّل USB-Debugging على هاتفك
- افتح الطرفية وأدخل:
```bash
adb logcat --pid=$(adb shell pidof -s 'com.nextcloud.client') > logcatOutput.txt
```
> تأكد من تثبيت [adb](https://developer.android.com/studio/releases/platform-tools.html)
### على ويندوز:
- حمّل [Minimal ADB and Fastboot](https://forum.xda-developers.com/t/tool-minimal-adb-and-fastboot-2-9-18.2317790/#post-42407269)
- فعّل USB-Debugging
- افتح البرنامج وأدخل:
```bash
adb shell pidof -s 'com.nextcloud.client'
```
- استخدم الناتج كـ `<processID>` في الأمر التالي:
```bash
adb logcat --pid=<processID> > "%USERPROFILE%\Downloads\logcatOutput.txt"
```
### على الجهاز (مع صلاحيات root):
```bash
su
logcat -d --pid $(pidof -s com.nextcloud.client) -f /sdcard/logcatOutput.txt
```
أو استخدم تطبيقات مثل [CatLog](https://play.google.com/store/apps/details?id=com.nolanlawson.logcat) أو [aLogcat](https://play.google.com/store/apps/details?id=org.jtb.alogcat)
## النسخة التطويرية 🛠️
- [تحميل مباشر للـ APK](https://download.nextcloud.com/android/dev/latest.apk)
- [F-Droid النسخة التجريبية](https://f-droid.org/en/packages/com.nextcloud.android.beta/)
## المشاكل المعروفة والأسئلة الشائعة
### الإشعارات الفورية لا تعمل في نسخ F-Droid
بسبب اعتمادها على خدمات Google Play، لا تعمل الإشعارات الفورية في نسخ F-Droid حاليًا.
+2 -3
View File
@@ -116,8 +116,8 @@ android {
defaultConfig {
applicationId = "com.nextcloud.client"
minSdk = 27
targetSdk = 36
compileSdk = 36
targetSdk = 35
compileSdk = 35
buildConfigField "boolean", "CI", ciBuild.toString()
buildConfigField "boolean", "RUNTIME_PERF_ANALYSIS", perfAnalysis.toString()
@@ -296,7 +296,6 @@ 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,8 +119,7 @@ class SyncedFoldersActivityIT : AbstractIT() {
onIdleSync {
EspressoIdlingResource.increment()
val dialog = sut.buildPowerCheckDialog()
sut.showPowerCheckDialog()
dialog.show()
EspressoIdlingResource.decrement()
val screenShotName = createName(testClassName + "_" + "showPowerCheckDialog", "")
@@ -1,90 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.extensions
import android.graphics.Bitmap
import android.graphics.Color
import androidx.exifinterface.media.ExifInterface
import com.nextcloud.utils.rotateBitmapViaExif
import junit.framework.TestCase.assertEquals
import org.junit.Test
class BitmapRotationTests {
private fun createTestBitmap(): Bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888).apply {
setPixel(0, 0, Color.RED)
setPixel(1, 0, Color.GREEN)
setPixel(0, 1, Color.BLUE)
setPixel(1, 1, Color.YELLOW)
}
@Test
fun testRotateBitmapViaExifWhenGivenNullBitmapShouldReturnNull() {
val rotated = null.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_90)
assertEquals(null, rotated)
}
@Test
fun testRotateBitmapViaExifWhenGivenNormalOrientationShouldReturnSameBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_NORMAL)
assertEquals(bmp, rotated)
}
@Test
fun testRotateBitmapViaExifWhenGivenRotate90ShouldReturnRotatedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_90)!!
assertEquals(bmp.width, rotated.height)
assertEquals(bmp.height, rotated.width)
assertEquals(Color.BLUE, rotated.getPixel(0, 0))
assertEquals(Color.RED, rotated.getPixel(1, 0))
assertEquals(Color.YELLOW, rotated.getPixel(0, 1))
assertEquals(Color.GREEN, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenRotate180ShouldReturnRotatedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_ROTATE_180)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.YELLOW, rotated.getPixel(0, 0))
assertEquals(Color.BLUE, rotated.getPixel(1, 0))
assertEquals(Color.GREEN, rotated.getPixel(0, 1))
assertEquals(Color.RED, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenFlipHorizontalShouldReturnFlippedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_FLIP_HORIZONTAL)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.GREEN, rotated.getPixel(0, 0))
assertEquals(Color.RED, rotated.getPixel(1, 0))
assertEquals(Color.YELLOW, rotated.getPixel(0, 1))
assertEquals(Color.BLUE, rotated.getPixel(1, 1))
}
@Test
fun testRotateBitmapViaExifWhenGivenFlipVerticalShouldReturnFlippedBitmap() {
val bmp = createTestBitmap()
val rotated = bmp.rotateBitmapViaExif(ExifInterface.ORIENTATION_FLIP_VERTICAL)!!
assertEquals(bmp.width, rotated.width)
assertEquals(bmp.height, rotated.height)
assertEquals(Color.BLUE, rotated.getPixel(0, 0))
assertEquals(Color.YELLOW, rotated.getPixel(1, 0))
assertEquals(Color.RED, rotated.getPixel(0, 1))
assertEquals(Color.GREEN, rotated.getPixel(1, 1))
}
}
@@ -1,78 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.extensions
import android.graphics.Bitmap
import android.graphics.Color
import androidx.exifinterface.media.ExifInterface
import com.nextcloud.utils.extensions.getExifOrientation
import junit.framework.TestCase.assertEquals
import org.junit.After
import org.junit.Test
import java.io.File
class GetExifOrientationTests {
private val tempFiles = mutableListOf<File>()
@Suppress("MagicNumber")
private fun createTempImageFile(): File {
val file = File.createTempFile("test_image", ".jpg")
tempFiles.add(file)
val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888).apply {
setPixel(0, 0, Color.RED)
setPixel(1, 0, Color.GREEN)
setPixel(0, 1, Color.BLUE)
setPixel(1, 1, Color.YELLOW)
}
file.outputStream().use { out ->
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out)
}
return file
}
@After
fun cleanup() {
tempFiles.forEach { it.delete() }
}
@Test
fun testGetExifOrientationWhenExifIsRotate90ShouldReturnRotate90() {
val file = createTempImageFile()
val exif = ExifInterface(file.absolutePath)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_90.toString())
exif.saveAttributes()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_ROTATE_90, orientation)
}
@Test
fun testGetExifOrientationWhenExifIsRotate180ShouldReturnRotate180() {
val file = createTempImageFile()
val exif = ExifInterface(file.absolutePath)
exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_ROTATE_180.toString())
exif.saveAttributes()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_ROTATE_180, orientation)
}
@Test
fun testGetExifOrientationWhenExifIsUndefinedShouldReturnUndefined() {
val file = createTempImageFile()
val orientation = getExifOrientation(file.absolutePath)
assertEquals(ExifInterface.ORIENTATION_UNDEFINED, orientation)
}
}
@@ -1,204 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
package com.nextcloud.utils
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
@Suppress("TooManyFunctions")
class FileHelperTest {
private lateinit var testDirectory: File
@Before
fun setup() {
testDirectory = Files.createTempDirectory("test").toFile()
}
@After
fun tearDown() {
testDirectory.deleteRecursively()
}
@Test
fun testListDirectoryEntriesWhenGivenNullDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(null, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenNonExistentDirectoryShouldReturnEmptyList() {
val nonExistent = File(testDirectory, "does_not_exist")
val result = FileHelper.listDirectoryEntries(nonExistent, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenFileInsteadOfDirectoryShouldReturnEmptyList() {
val file = File(testDirectory, "test.txt")
file.createNewFile()
val result = FileHelper.listDirectoryEntries(file, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenEmptyDirectoryShouldReturnEmptyList() {
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenFetchingFoldersShouldReturnOnlyFolders() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertEquals(2, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testListDirectoryEntriesWhenFetchingFilesShouldReturnOnlyFiles() {
File(testDirectory, "folder1").mkdir()
File(testDirectory, "folder2").mkdir()
File(testDirectory, "file1.txt").createNewFile()
File(testDirectory, "file2.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(2, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenStartIndexProvidedShouldSkipCorrectNumberOfItems() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(3, result.size)
}
@Test
fun testListDirectoryEntriesWhenMaxItemsProvidedShouldLimitResults() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 5, false)
assertEquals(5, result.size)
}
@Test
fun testListDirectoryEntriesWhenGivenStartIndexAndMaxItemsShouldReturnCorrectSubset() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 3, 4, false)
assertEquals(4, result.size)
}
@Test
fun testListDirectoryEntriesWhenStartIndexBeyondAvailableShouldReturnEmptyList() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 10, 5, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsBeyondAvailableShouldReturnAllItems() {
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 100, false)
assertEquals(3, result.size)
}
@Test
fun testListDirectoryEntriesWhenFetchingFoldersWithOffsetShouldSkipCorrectly() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
for (i in 1..3) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, true)
assertEquals(3, result.size)
assertTrue(result.all { it.isDirectory })
}
@Test
fun testListDirectoryEntriesWhenFetchingFilesWithOffsetShouldSkipCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 2, 10, false)
assertEquals(3, result.size)
assertTrue(result.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenGivenOnlyFoldersAndFetchingFilesShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "folder$i").mkdir()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenOnlyFilesAndFetchingFoldersShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenMaxItemsIsZeroShouldReturnEmptyList() {
for (i in 1..5) File(testDirectory, "file$i.txt").createNewFile()
val result = FileHelper.listDirectoryEntries(testDirectory, 0, 0, false)
assertTrue(result.isEmpty())
}
@Test
fun testListDirectoryEntriesWhenGivenMixedContentShouldFilterCorrectly() {
for (i in 1..3) File(testDirectory, "folder$i").mkdir()
for (i in 1..7) File(testDirectory, "file$i.txt").createNewFile()
val folders = FileHelper.listDirectoryEntries(testDirectory, 0, 10, true)
val files = FileHelper.listDirectoryEntries(testDirectory, 0, 10, false)
assertEquals(3, folders.size)
assertEquals(7, files.size)
assertTrue(folders.all { it.isDirectory })
assertTrue(files.all { it.isFile })
}
@Test
fun testListDirectoryEntriesWhenPaginatingFoldersShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "folder$i").mkdir()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 3, true)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 3, 3, true)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 6, 3, true)
val page4 = FileHelper.listDirectoryEntries(testDirectory, 9, 3, true)
assertEquals(3, page1.size)
assertEquals(3, page2.size)
assertEquals(3, page3.size)
assertEquals(1, page4.size)
}
@Test
fun testListDirectoryEntriesWhenPaginatingFilesShouldWorkCorrectly() {
for (i in 1..10) File(testDirectory, "file$i.txt").createNewFile()
val page1 = FileHelper.listDirectoryEntries(testDirectory, 0, 4, false)
val page2 = FileHelper.listDirectoryEntries(testDirectory, 4, 4, false)
val page3 = FileHelper.listDirectoryEntries(testDirectory, 8, 4, false)
assertEquals(4, page1.size)
assertEquals(4, page2.size)
assertEquals(2, page3.size)
}
}
@@ -18,7 +18,6 @@ import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.account.UserAccountManagerImpl;
import com.nextcloud.client.database.entity.UploadEntityKt;
import com.nextcloud.test.RandomStringGenerator;
import com.owncloud.android.AbstractIT;
import com.owncloud.android.MainApp;
@@ -109,7 +108,7 @@ public class UploadStorageManagerTest extends AbstractIT {
OCUpload upload = createUpload(account);
uploads.add(upload);
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
uploadsStorageManager.storeUpload(upload);
}
OCUpload[] storedUploads = uploadsStorageManager.getAllStoredUploads();
@@ -152,14 +151,17 @@ public class UploadStorageManagerTest extends AbstractIT {
account.name);
corruptUpload.setLocalPath(null);
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(corruptUpload));
uploadsStorageManager.storeUpload(corruptUpload);
uploadsStorageManager.getAllStoredUploads();
}
@Test
public void getById() {
OCUpload upload = createUpload(account);
long id = uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(upload));
long id = uploadsStorageManager.storeUpload(upload);
OCUpload newUpload = uploadsStorageManager.getUploadById(id);
assertNotNull(newUpload);
@@ -176,7 +178,7 @@ public class UploadStorageManagerTest extends AbstractIT {
private void insertUploads(Account account, int rowsToInsert) {
for (int i = 0; i < rowsToInsert; i++) {
uploadsStorageManager.uploadDao.insertOrReplace(UploadEntityKt.toUploadEntity(createUpload(account)));
uploadsStorageManager.storeUpload(createUpload(account));
}
}
@@ -27,8 +27,8 @@ public class FileDisplayActivityTest extends AbstractIT {
InstrumentationRegistry.getInstrumentation().runOnMainSync(() -> {
Activity activity =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED).iterator().next();
if (activity instanceof WhatsNewActivity whatsNewActivity) {
whatsNewActivity.getOnBackPressedDispatcher().onBackPressed();
if (activity instanceof WhatsNewActivity) {
activity.onBackPressed();
}
});
scenario.recreate();
@@ -822,7 +822,7 @@ class FileDetailSharingFragmentIT : AbstractIT() {
val processFragment =
activity.supportFragmentManager.findFragmentByTag(FileDetailsSharingProcessFragment.TAG) as
FileDetailsSharingProcessFragment
processFragment.activity?.onBackPressedDispatcher?.onBackPressed()
processFragment.onBackPressed()
}
}
}
+1 -4
View File
@@ -121,7 +121,7 @@
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:enableOnBackInvokedCallback="true"
android:enableOnBackInvokedCallback="false"
android:theme="@style/Theme.ownCloud.Toolbar"
android:usesCleartextTraffic="true"
tools:ignore="UnusedAttribute"
@@ -353,7 +353,6 @@
<activity
android:name=".ui.activity.SettingsActivity"
android:exported="false"
android:enableOnBackInvokedCallback="false"
android:theme="@style/PreferenceTheme" />
<activity
android:name=".ui.preview.PreviewImageActivity"
@@ -585,8 +584,6 @@
</intent-filter>
</receiver>
<receiver android:name="com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerReceiver" android:exported="false" />
<activity
android:name=".ui.activity.CopyToClipboardActivity"
android:exported="false"
@@ -9,12 +9,28 @@
*/
package com.nextcloud.android.sso;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.util.EncodingUtil;
import java.util.Vector;
public class PatchMethod extends PostMethod {
/**
* The buffered request body consisting of <code>NameValuePair</code>s.
*/
private Vector params = new Vector();
/**
* No-arg constructor.
*/
public PatchMethod() {
super();
}
/**
* Constructor specifying a URI.
*
@@ -42,7 +58,11 @@ public class PatchMethod extends PostMethod {
* @since 2.0beta1
*/
protected boolean hasRequestContent() {
return super.hasRequestContent();
if (!this.params.isEmpty()) {
return true;
} else {
return super.hasRequestContent();
}
}
/**
@@ -51,6 +71,7 @@ public class PatchMethod extends PostMethod {
* @since 2.0beta1
*/
protected void clearRequestBody() {
this.params.clear();
super.clearRequestBody();
}
@@ -61,6 +82,19 @@ public class PatchMethod extends PostMethod {
* @since 3.0
*/
protected RequestEntity generateRequestEntity() {
return super.generateRequestEntity();
if (!this.params.isEmpty()) {
// Use a ByteArrayRequestEntity instead of a StringRequestEntity.
// This is to avoid potential encoding issues. Form url encoded strings
// are ASCII by definition but the content type may not be. Treating the content
// as bytes allows us to keep the current charset without worrying about how
// this charset will effect the encoding of the form url encoded string.
String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
return new ByteArrayRequestEntity(
EncodingUtil.getAsciiBytes(content),
FORM_URL_ENCODED_CONTENT_TYPE
);
} else {
return super.generateRequestEntity();
}
}
}
@@ -20,7 +20,6 @@ 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
@@ -97,7 +96,6 @@ 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,6 +17,15 @@ 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,24 +9,21 @@ 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 *
SELECT ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_LOCAL_PATH}
FROM ${ProviderMeta.ProviderTableMeta.FILESYSTEM_TABLE_NAME}
WHERE ${ProviderMeta.ProviderTableMeta.FILESYSTEM_SYNCED_FOLDER_ID} = :syncedFolderId
AND ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_SENT_FOR_UPLOAD} = 0
AND ${ProviderMeta.ProviderTableMeta.FILESYSTEM_FILE_IS_FOLDER} = 0
AND ${ProviderMeta.ProviderTableMeta._ID} > :lastId
ORDER BY ${ProviderMeta.ProviderTableMeta._ID}
LIMIT :limit
"""
)
suspend fun getAutoUploadFilesEntities(syncedFolderId: String, limit: Int, lastId: Int): List<FilesystemEntity>
suspend fun getAutoUploadFiles(syncedFolderId: String): List<String>
@Query(
"""
@@ -1,26 +0,0 @@
/*
* 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,8 +8,6 @@
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
@@ -29,52 +27,4 @@ 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,9 +10,6 @@ package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.nextcloud.client.preferences.SubFolderRule
import com.owncloud.android.datamodel.MediaFolderType
import com.owncloud.android.datamodel.SyncedFolder
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.SYNCED_FOLDERS_TABLE_NAME)
@@ -53,40 +50,3 @@ data class SyncedFolderEntity(
@ColumnInfo(name = ProviderTableMeta.SYNCED_FOLDER_LAST_SCAN_TIMESTAMP_MS)
val lastScanTimestampMs: Long?
)
fun SyncedFolderEntity.toSyncedFolder(): SyncedFolder = SyncedFolder(
// id
(this.id ?: SyncedFolder.UNPERSISTED_ID).toLong(),
// localPath
this.localPath ?: "",
// remotePath
this.remotePath ?: "",
// wifiOnly
this.wifiOnly == 1,
// chargingOnly
this.chargingOnly == 1,
// existing
this.existing == 1,
// subfolderByDate
this.subfolderByDate == 1,
// account
this.account ?: "",
// uploadAction
this.uploadAction ?: 0,
// nameCollisionPolicy
this.nameCollisionPolicy ?: 0,
// enabled
this.enabled == 1,
// timestampMs
(this.enabledTimestampMs ?: SyncedFolder.EMPTY_ENABLED_TIMESTAMP_MS).toLong(),
// type
MediaFolderType.getById(this.type ?: MediaFolderType.CUSTOM.id),
// hidden
this.hidden == 1,
// subFolderRule
this.subFolderRule?.let { SubFolderRule.entries[it] },
// excludeHidden
this.excludeHidden == 1,
// lastScanTimestampMs
this.lastScanTimestampMs ?: SyncedFolder.NOT_SCANNED_YET
)
@@ -1,7 +1,6 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[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
@@ -79,33 +78,3 @@ 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,7 +17,6 @@ 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;
@@ -76,8 +75,6 @@ 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 -> {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
true
}
else -> false
@@ -10,7 +10,6 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.OnBackPressedCallback
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.nextcloud.client.di.Injectable
@@ -47,7 +46,6 @@ class EtmActivity :
onPageChanged(it)
}
)
handleOnBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
@@ -60,17 +58,11 @@ class EtmActivity :
else -> super.onOptionsItemSelected(item)
}
private fun handleOnBackPressed() {
onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
val handledByVm = vm.onBackPressed()
if (!handledByVm) {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
})
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (!vm.onBackPressed()) {
super.onBackPressed()
}
}
private fun onPageChanged(page: EtmMenuEntry?) {
@@ -17,17 +17,14 @@ 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
@@ -64,8 +61,7 @@ class BackgroundJobFactory @Inject constructor(
private val viewThemeUtils: Provider<ViewThemeUtils>,
private val localBroadcastManager: Provider<LocalBroadcastManager>,
private val generatePdfUseCase: GeneratePDFUseCase,
private val syncedFolderProvider: SyncedFolderProvider,
private val database: NextcloudDatabase
private val syncedFolderProvider: SyncedFolderProvider
) : WorkerFactory() {
@SuppressLint("NewApi")
@@ -103,7 +99,6 @@ 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
}
}
@@ -178,8 +173,7 @@ class BackgroundJobFactory @Inject constructor(
connectivityService = connectivityService,
powerManagementService = powerManagementService,
syncedFolderProvider = syncedFolderProvider,
backgroundJobManager = backgroundJobManager.get(),
repository = FileSystemRepository(dao = database.fileSystemDao())
backgroundJobManager = backgroundJobManager.get()
)
private fun createOfflineSyncWork(context: Context, params: WorkerParameters): OfflineSyncWork = OfflineSyncWork(
@@ -289,12 +283,4 @@ class BackgroundJobFactory @Inject constructor(
params,
accountManager.user
)
private fun createFolderDownloadWorker(context: Context, params: WorkerParameters): FolderDownloadWorker =
FolderDownloadWorker(
accountManager,
context,
viewThemeUtils.get(),
params
)
}
@@ -122,10 +122,13 @@ interface BackgroundJobManager {
fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder)
fun startAutoUploadImmediately(
/**
* Immediately start File Sync job for given syncFolderID.
*/
fun startImmediateFilesSyncJob(
syncedFolder: SyncedFolder,
overridePowerSaving: Boolean = false,
contentUris: Array<String?> = arrayOf()
changedFiles: Array<String?> = arrayOf()
)
fun cancelTwoWaySyncJob()
@@ -140,10 +143,12 @@ interface BackgroundJobManager {
fun startFilesUploadJob(user: User, uploadIds: LongArray, showSameFileAlreadyExistsNotification: Boolean)
fun getFileUploads(user: User): LiveData<List<JobInfo>>
fun cancelFilesUploadJob(user: User)
fun isStartFileUploadJobScheduled(accountName: String): Boolean
fun isStartFileUploadJobScheduled(user: User): Boolean
fun cancelFilesDownloadJob(user: User, fileId: Long)
fun isStartFileDownloadJobScheduled(user: User, fileId: Long): Boolean
@Suppress("LongParameterList")
fun startFileDownloadJob(
user: User,
@@ -171,6 +176,4 @@ interface BackgroundJobManager {
fun scheduleInternal2WaySync(intervalMinutes: Long)
fun cancelAllFilesDownloadJobs()
fun startMetadataSyncJob(currentDirPath: String)
fun downloadFolder(folder: OCFile, accountName: String)
fun cancelFolderDownload()
}
@@ -28,7 +28,6 @@ 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
@@ -94,7 +93,6 @@ 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"
@@ -509,16 +507,16 @@ internal class BackgroundJobManagerImpl(
)
}
override fun startAutoUploadImmediately(
override fun startImmediateFilesSyncJob(
syncedFolder: SyncedFolder,
overridePowerSaving: Boolean,
contentUris: Array<String?>
changedFiles: Array<String?>
) {
val syncedFolderID = syncedFolder.id
val arguments = Data.Builder()
.putBoolean(AutoUploadWorker.OVERRIDE_POWER_SAVING, overridePowerSaving)
.putStringArray(AutoUploadWorker.CONTENT_URIS, contentUris)
.putStringArray(AutoUploadWorker.CHANGED_FILES, changedFiles)
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
.build()
@@ -637,10 +635,10 @@ internal class BackgroundJobManagerImpl(
workManager.enqueue(request)
}
private fun startFileUploadJobTag(accountName: String): String = JOB_FILES_UPLOAD + accountName
private fun startFileUploadJobTag(user: User): String = JOB_FILES_UPLOAD + user.accountName
override fun isStartFileUploadJobScheduled(accountName: String): Boolean =
workManager.isWorkScheduled(startFileUploadJobTag(accountName))
override fun isStartFileUploadJobScheduled(user: User): Boolean =
workManager.isWorkScheduled(startFileUploadJobTag(user))
/**
* This method supports initiating uploads for various scenarios, including:
@@ -658,7 +656,7 @@ internal class BackgroundJobManagerImpl(
defaultDispatcherScope.launch {
val batchSize = FileUploadHelper.MAX_FILE_COUNT
val batches = uploadIds.toList().chunked(batchSize)
val tag = startFileUploadJobTag(user.accountName)
val tag = startFileUploadJobTag(user)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
@@ -704,6 +702,9 @@ internal class BackgroundJobManagerImpl(
private fun startFileDownloadJobTag(user: User, fileId: Long): String =
JOB_FOLDER_DOWNLOAD + user.accountName + fileId
override fun isStartFileDownloadJobScheduled(user: User, fileId: Long): Boolean =
workManager.isWorkScheduled(startFileDownloadJobTag(user, fileId))
override fun startFileDownloadJob(
user: User,
file: OCFile,
@@ -823,28 +824,4 @@ internal class BackgroundJobManagerImpl(
workManager.enqueueUniquePeriodicWork(JOB_INTERNAL_TWO_WAY_SYNC, ExistingPeriodicWorkPolicy.UPDATE, request)
}
override fun downloadFolder(folder: OCFile, accountName: String) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresStorageNotLow(true)
.build()
val data = Data.Builder()
.putLong(FolderDownloadWorker.FOLDER_ID, folder.fileId)
.putString(FolderDownloadWorker.ACCOUNT_NAME, accountName)
.build()
val request = oneTimeRequestBuilder(FolderDownloadWorker::class, JOB_DOWNLOAD_FOLDER)
.addTag(JOB_DOWNLOAD_FOLDER)
.setInputData(data)
.setConstraints(constraints)
.build()
workManager.enqueueUniqueWork(JOB_DOWNLOAD_FOLDER, ExistingWorkPolicy.APPEND_OR_REPLACE, request)
}
override fun cancelFolderDownload() {
workManager.cancelAllWorkByTag(JOB_DOWNLOAD_FOLDER)
}
}
@@ -1,27 +1,18 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[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.core.app.NotificationCompat
import androidx.work.CoroutineWorker
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.utils.ForegroundServiceHelper
import com.owncloud.android.R
import com.owncloud.android.datamodel.ForegroundServiceType
import com.owncloud.android.datamodel.SyncedFolderProvider
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.FilesSyncHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* This work is triggered when OS detects change in media folders.
@@ -30,113 +21,53 @@ import kotlinx.coroutines.withContext
*
* This job must not be started on API < 24.
*/
@Suppress("TooGenericExceptionCaught")
class ContentObserverWork(
private val context: Context,
appContext: Context,
private val params: WorkerParameters,
private val syncedFolderProvider: SyncedFolderProvider,
private val powerManagementService: PowerManagementService,
private val backgroundJobManager: BackgroundJobManager
) : CoroutineWorker(context, params) {
) : Worker(appContext, params) {
companion object {
private const val TAG = "🔍" + "ContentObserverWork"
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_CONTENT_OBSERVER
private const val NOTIFICATION_ID = 774
}
override fun doWork(): Result {
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
val workerName = BackgroundJobManagerImpl.formatClassTag(this@ContentObserverWork::class)
backgroundJobManager.logStartOfWorker(workerName)
Log_OC.d(TAG, "started")
try {
if (params.triggeredContentUris.isNotEmpty()) {
Log_OC.d(TAG, "📸 content observer detected file changes.")
val notificationTitle = context.getString(R.string.content_observer_work_notification_title)
val notification = createNotification(notificationTitle)
updateForegroundInfo(notification)
checkAndTriggerAutoUpload()
// prevent worker fail because of another worker
try {
backgroundJobManager.startMediaFoldersDetectionJob()
} catch (e: Exception) {
Log_OC.d(TAG, "⚠️ media folder detection job failed :$e")
}
} else {
Log_OC.d(TAG, "⚠️ triggeredContentUris is empty — nothing to sync.")
}
rescheduleSelf()
val result = Result.success()
backgroundJobManager.logEndOfWorker(workerName, result)
Log_OC.d(TAG, "finished")
result
} catch (e: Exception) {
Log_OC.e(TAG, "❌ Exception in ContentObserverWork: ${e.message}", e)
Result.retry()
if (params.triggeredContentUris.isNotEmpty()) {
Log_OC.d(TAG, "File-sync Content Observer detected files change")
checkAndStartFileSyncJob()
backgroundJobManager.startMediaFoldersDetectionJob()
} else {
Log_OC.d(TAG, "triggeredContentUris empty")
}
recheduleSelf()
val result = Result.success()
backgroundJobManager.logEndOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class), result)
return result
}
private suspend fun updateForegroundInfo(notification: Notification) {
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
NOTIFICATION_ID,
notification,
ForegroundServiceType.DataSync
)
setForeground(foregroundInfo)
}
private fun createNotification(title: String): Notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_find_in_page)
.setOngoing(true)
.setSound(null)
.setVibrate(null)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSilent(true)
.build()
/**
* Re-schedules this observer to ensure continuous monitoring of media changes.
*/
private fun rescheduleSelf() {
Log_OC.d(TAG, "🔁 Rescheduling ContentObserverWork for continued observation.")
private fun recheduleSelf() {
backgroundJobManager.scheduleContentObserverJob()
}
private suspend fun checkAndTriggerAutoUpload() = withContext(Dispatchers.IO) {
if (powerManagementService.isPowerSavingEnabled) {
Log_OC.w(TAG, "⚡ Power saving mode active — skipping file sync.")
return@withContext
}
val enabledFoldersCount = syncedFolderProvider.countEnabledSyncedFolders()
if (enabledFoldersCount <= 0) {
Log_OC.w(TAG, "🚫 No enabled synced folders found — skipping file sync.")
return@withContext
}
val contentUris = params.triggeredContentUris.map { uri ->
// adds uri strings e.g. content://media/external/images/media/2281
uri.toString()
}.toTypedArray()
Log_OC.d(TAG, "📄 Content uris detected")
try {
FilesSyncHelper.startAutoUploadImmediatelyWithContentUris(
private fun checkAndStartFileSyncJob() {
if (!powerManagementService.isPowerSavingEnabled && syncedFolderProvider.countEnabledSyncedFolders() > 0) {
val changedFiles = mutableListOf<String>()
for (uri in params.triggeredContentUris) {
changedFiles.add(uri.toString())
}
FilesSyncHelper.startFilesSyncForAllFolders(
syncedFolderProvider,
backgroundJobManager,
false,
contentUris
changedFiles.toTypedArray()
)
Log_OC.d(TAG, "✅ auto upload triggered successfully for ${contentUris.size} file(s).")
} catch (e: Exception) {
Log_OC.e(TAG, "❌ Failed to start auto upload for changed files: ${e.message}", e)
} else {
Log_OC.w(TAG, "cant startFilesSyncForAllFolders")
}
}
companion object {
val TAG: String = ContentObserverWork::class.java.simpleName
}
}
@@ -17,16 +17,14 @@ import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.database.entity.UploadEntity
import com.nextcloud.client.database.entity.toOCUpload
import com.nextcloud.client.database.entity.toUploadEntity
import com.nextcloud.client.database.NextcloudDatabase
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.upload.FileUploadWorker
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.client.preferences.SubFolderRule
import com.nextcloud.utils.ForegroundServiceHelper
import com.nextcloud.utils.extensions.updateStatus
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.datamodel.ArbitraryDataProviderImpl
import com.owncloud.android.datamodel.FileDataStorageManager
@@ -45,6 +43,7 @@ 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
@@ -62,14 +61,13 @@ class AutoUploadWorker(
private val connectivityService: ConnectivityService,
private val powerManagementService: PowerManagementService,
private val syncedFolderProvider: SyncedFolderProvider,
private val backgroundJobManager: BackgroundJobManager,
private val repository: FileSystemRepository
private val backgroundJobManager: BackgroundJobManager
) : CoroutineWorker(context, params) {
companion object {
const val TAG = "🔄📤" + "AutoUpload"
const val OVERRIDE_POWER_SAVING = "overridePowerSaving"
const val CONTENT_URIS = "content_uris"
const val CHANGED_FILES = "changedFiles"
const val SYNCED_FOLDER_ID = "syncedFolderId"
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD
@@ -85,23 +83,24 @@ class AutoUploadWorker(
override suspend fun doWork(): Result {
return try {
val syncFolderId = inputData.getLong(SYNCED_FOLDER_ID, -1)
syncedFolder = syncedFolderProvider.getSyncedFolderByID(syncFolderId)
?.takeIf { it.isEnabled } ?: return Result.failure()
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
// initial notification
val notification = createNotification(context.getString(R.string.upload_files))
updateForegroundInfo(notification)
/**
* Receives from [com.nextcloud.client.jobs.ContentObserverWork.checkAndTriggerAutoUpload]
*/
val contentUris = inputData.getStringArray(CONTENT_URIS)
val changedFiles = inputData.getStringArray(CHANGED_FILES)
if (canExitEarly(contentUris, syncFolderId)) {
if (canExitEarly(changedFiles, syncFolderId)) {
return Result.retry()
}
collectFileChangesFromContentObserverWork(contentUris)
collectFileChangesFromContentObserverWork(changedFiles)
updateNotification()
uploadFiles(syncedFolder)
@@ -147,10 +146,11 @@ class AutoUploadWorker(
.build()
@Suppress("TooGenericExceptionCaught")
private fun getStartNotificationTitle(): Pair<String, String>? = try {
private fun getStartNotificationTitle(): Pair<String, String>? {
val localPath = syncedFolder.localPath
val remotePath = syncedFolder.remotePath
if (localPath.isBlank() || remotePath.isBlank()) {
return if (localPath.isBlank() || remotePath.isBlank()) {
null
} else {
try {
@@ -159,12 +159,10 @@ class AutoUploadWorker(
null
}
}
} catch (_: Exception) {
null
}
@Suppress("ReturnCount")
private fun canExitEarly(contentUris: Array<String>?, syncedFolderID: Long): Boolean {
private fun canExitEarly(changedFiles: 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")
@@ -181,16 +179,19 @@ class AutoUploadWorker(
return true
}
val totalScanInterval = syncedFolder.getTotalScanInterval(connectivityService, powerManagementService)
val calculatedScanInterval =
FilesSyncHelper.calculateScanInterval(syncedFolder, connectivityService, powerManagementService)
val totalScanInterval = (syncedFolder.lastScanTimestampMs + calculatedScanInterval)
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 && contentUris.isNullOrEmpty() && !overridePowerSaving) {
if (!passedScanInterval && changedFiles.isNullOrEmpty() && !overridePowerSaving) {
Log_OC.w(
TAG,
"skipped since started before scan interval and nothing todo: " + syncedFolder.localPath
@@ -201,56 +202,61 @@ class AutoUploadWorker(
return false
}
/**
* Instead of scanning the entire local folder, optional content URIs can be passed to the worker
* to detect only the relevant changes.
*/
@Suppress("MagicNumber", "TooGenericExceptionCaught")
private suspend fun collectFileChangesFromContentObserverWork(contentUris: Array<String>?) = try {
@Suppress("MagicNumber")
private suspend fun collectFileChangesFromContentObserverWork(changedFiles: Array<String>?) =
withContext(Dispatchers.IO) {
if (contentUris.isNullOrEmpty()) {
if (changedFiles.isNullOrEmpty()) {
// Check every file in synced folder for changes and update
// filesystemDataProvider database (potentially needs a long time)
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
} else {
val isContentUrisStored = FilesSyncHelper.insertChangedEntries(syncedFolder, contentUris)
if (!isContentUrisStored) {
Log_OC.w(
TAG,
"changed content uris not stored, fallback to insert all db entries to not lose files"
)
FilesSyncHelper.insertAllDBEntriesForSyncedFolder(syncedFolder)
}
FilesSyncHelper.insertChangedEntries(syncedFolder, changedFiles)
}
syncedFolder.lastScanTimestampMs = System.currentTimeMillis()
syncedFolderProvider.updateSyncFolder(syncedFolder)
}
} catch (e: Exception) {
Log_OC.d(TAG, "Exception collectFileChangesFromContentObserverWork: $e")
}
private fun prepareDateFormat(): SimpleDateFormat {
val currentLocale = context.resources.configuration.locales[0]
return SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale).apply {
timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
}
val dateFormat = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale)
dateFormat.timeZone = TimeZone.getTimeZone(TimeZone.getDefault().id)
return dateFormat
}
private fun getUserOrReturn(syncedFolder: SyncedFolder): User? {
val optionalUser = userAccountManager.getUser(syncedFolder.account)
if (!optionalUser.isPresent) {
Log_OC.w(TAG, "user not present")
Log_OC.w(TAG, "uploadFilesFromFolder skipped 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, "light version is used")
Log_OC.d(TAG, "uploadFilesFromFolder light version is used")
val arbitraryDataProvider = ArbitraryDataProviderImpl(context)
val needsCharging = context.resources.getBoolean(R.bool.syncedFolder_light_on_charging)
val needsWifi = arbitraryDataProvider.getBooleanValue(
@@ -262,113 +268,33 @@ class AutoUploadWorker(
Log_OC.d(TAG, "upload action is: $uploadAction")
Triple(needsCharging, needsWifi, uploadAction)
} else {
Log_OC.d(TAG, "not light version is used")
Log_OC.d(TAG, "uploadFilesFromFolder not light version is used")
Triple(syncedFolder.isChargingOnly, syncedFolder.isWifiOnly, syncedFolder.uploadAction)
}
}
@Suppress("LongMethod", "DEPRECATION", "TooGenericExceptionCaught")
@Suppress("LongMethod", "DEPRECATION")
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]
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 {
pathsAndMimes.forEach { (localPath, remotePath, _) ->
val upload = OCUpload(localPath, remotePath, user.accountName).apply {
nameCollisionPolicy = syncedFolder.nameCollisionPolicy
isUseWifiOnly = needsWifi
isWhileChargingOnly = needsCharging
@@ -377,10 +303,20 @@ class AutoUploadWorker(
isCreateRemoteFolder = true
localAction = uploadAction
}
uploadEntity = upload.toUploadEntity()
}
return uploadEntity to upload
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")
}
}
}
private fun createUploadFileOperation(upload: OCUpload, user: User): UploadFileOperation = UploadFileOperation(
@@ -410,12 +346,14 @@ 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,41 +15,28 @@ import java.io.File
class FileSystemRepository(private val dao: FileSystemDao) {
companion object {
private const val TAG = "FilesystemRepository"
const val BATCH_SIZE = 50
}
@Suppress("NestedBlockDepth")
suspend fun getFilePathsWithIds(syncedFolder: SyncedFolder, lastId: Int): List<Pair<String, Int>> {
suspend fun getAutoUploadFiles(syncedFolder: SyncedFolder): Set<String> {
val syncedFolderId = syncedFolder.id.toString()
Log_OC.d(TAG, "Fetching candidate files for syncedFolderId = $syncedFolderId")
val entities = dao.getAutoUploadFilesEntities(syncedFolderId, BATCH_SIZE, lastId)
val filtered = mutableListOf<Pair<String, Int>>()
val candidatePaths = dao.getAutoUploadFiles(syncedFolderId)
val localPathsToUpload = mutableSetOf<String>()
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")
}
}
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)
}
}
return filtered
return localPathsToUpload
}
@Suppress("TooGenericExceptionCaught")
@@ -63,4 +50,8 @@ 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,12 +9,10 @@ package com.nextcloud.client.jobs.download
import com.nextcloud.client.account.User
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
import com.owncloud.android.MainApp
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.DownloadFileOperation
import com.owncloud.android.operations.DownloadType
import com.owncloud.android.utils.MimeTypeUtil
@@ -31,7 +29,6 @@ class FileDownloadHelper {
companion object {
private var instance: FileDownloadHelper? = null
private const val TAG = "FileDownloadHelper"
fun instance(): FileDownloadHelper = instance ?: synchronized(this) {
instance ?: FileDownloadHelper().also { instance = it }
@@ -47,11 +44,17 @@ class FileDownloadHelper {
return false
}
return if (file.isFolder) {
FolderDownloadWorker.isDownloading(file.fileId)
} else {
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
}
val fileStorageManager = FileDataStorageManager(user, MainApp.getAppContext().contentResolver)
val topParentId = fileStorageManager.getTopParentId(file)
val isJobScheduled = backgroundJobManager.isStartFileDownloadJobScheduled(user, file.fileId)
return isJobScheduled ||
if (file.isFolder) {
FileDownloadWorker.isDownloadingFolder(file.fileId) ||
backgroundJobManager.isStartFileDownloadJobScheduled(user, topParentId)
} else {
FileDownloadWorker.isDownloading(user.accountName, file.fileId)
}
}
fun cancelPendingOrCurrentDownloads(user: User?, files: List<OCFile>?) {
@@ -138,14 +141,4 @@ class FileDownloadHelper {
conflictUploadId
)
}
fun downloadFolder(folder: OCFile?, accountName: String) {
if (folder == null) {
Log_OC.e(TAG, "folder cannot be null, cant sync")
return
}
backgroundJobManager.downloadFolder(folder, accountName)
}
fun cancelFolderDownload() = backgroundJobManager.cancelFolderDownload()
}
@@ -24,6 +24,7 @@ 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
@@ -44,6 +45,7 @@ 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")
@@ -61,6 +63,7 @@ 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 {
@@ -72,6 +75,8 @@ 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"
@@ -165,6 +170,10 @@ 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?
@@ -1,167 +0,0 @@
/*
* 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
}
}
}
@@ -1,113 +0,0 @@
/*
* 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)
}
}
@@ -1,25 +0,0 @@
/*
* 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,14 +7,11 @@
*/
package com.nextcloud.client.jobs.upload
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
import com.nextcloud.client.database.entity.toOCUpload
import com.nextcloud.client.database.entity.toUploadEntity
import com.nextcloud.client.device.BatteryStatus
import com.nextcloud.client.device.PowerManagementService
import com.nextcloud.client.jobs.BackgroundJobManager
@@ -23,7 +20,6 @@ import com.nextcloud.client.network.Connectivity
import com.nextcloud.client.network.ConnectivityService
import com.nextcloud.utils.extensions.getUploadIds
import com.owncloud.android.MainApp
import com.owncloud.android.R
import com.owncloud.android.datamodel.FileDataStorageManager
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.datamodel.UploadsStorageManager
@@ -39,12 +35,13 @@ import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation
import com.owncloud.android.lib.resources.files.model.RemoteFile
import com.owncloud.android.operations.RemoveFileOperation
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.utils.DisplayUtils
import com.owncloud.android.utils.FileUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Semaphore
import javax.inject.Inject
@@ -208,7 +205,7 @@ class FileUploadHelper {
showSameFileAlreadyExistsNotification: Boolean = true
) {
val uploads = localPaths.mapIndexed { index, localPath ->
val result = OCUpload(localPath, remotePaths[index], user.accountName).apply {
OCUpload(localPath, remotePaths[index], user.accountName).apply {
this.nameCollisionPolicy = nameCollisionPolicy
isUseWifiOnly = requiresWifi
isWhileChargingOnly = requiresCharging
@@ -217,30 +214,47 @@ 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) {
uploadsStorageManager.uploadDao.deleteByAccountAndRemotePath(accountName, remotePath)
}
try {
val user = accountManager.getUser(accountName).get()
fun updateUploadStatus(remotePath: String, accountName: String, status: UploadStatus) {
ioScope.launch {
uploadsStorageManager.uploadDao.updateStatus(remotePath, accountName, status.value)
// need to update now table in mUploadsStorageManager,
// since the operation will not get to be run by FileUploader#uploadFile
uploadsStorageManager.removeUpload(accountName, remotePath)
val uploadIds = uploadsStorageManager.getCurrentUploadIds(user.accountName)
cancelAndRestartUploadJob(user, uploadIds)
} catch (e: NoSuchElementException) {
Log_OC.e(TAG, "Error cancelling current upload because user does not exist!: " + e.message)
}
}
fun getUploadsByStatus(accountName: String, status: UploadStatus, onCompleted: (Array<OCUpload>) -> Unit) {
fun cancelFileUpload(remotePath: String, accountName: String) {
ioScope.launch {
val result =
uploadsStorageManager.uploadDao.getUploadsByStatus(accountName, status.value)
.map { it.toOCUpload(null) }.toTypedArray()
onCompleted(result)
val upload = uploadsStorageManager.getUploadByRemotePath(remotePath)
if (upload != null) {
cancelFileUploads(listOf(upload), accountName)
} else {
Log_OC.e(TAG, "Error cancelling current upload because upload does not exist!")
}
}
}
fun cancelFileUploads(uploads: List<OCUpload>, accountName: String) {
for (upload in uploads) {
upload.uploadStatus = UploadStatus.UPLOAD_CANCELLED
uploadsStorageManager.updateUpload(upload)
}
try {
val user = accountManager.getUser(accountName).get()
cancelAndRestartUploadJob(user, uploads.getUploadIds())
} catch (e: NoSuchElementException) {
Log_OC.e(TAG, "Error restarting upload job because user does not exist!: " + e.message)
}
}
@@ -252,16 +266,26 @@ class FileUploadHelper {
}
@Suppress("ReturnCount")
fun isUploading(remotePath: String?, accountName: String?): Boolean {
accountName ?: return false
if (!backgroundJobManager.isStartFileUploadJobScheduled(accountName)) {
fun isUploading(user: User?, file: OCFile?): Boolean {
if (user == null || file == null || !backgroundJobManager.isStartFileUploadJobScheduled(user)) {
return false
}
remotePath ?: return false
val upload = uploadsStorageManager.uploadDao.getByRemotePath(remotePath)
return upload?.status == UploadStatus.UPLOAD_IN_PROGRESS.value ||
FileUploadWorker.isUploading(remotePath, accountName)
val uploadCompletableFuture = CompletableFuture.supplyAsync {
uploadsStorageManager.getUploadByRemotePath(file.remotePath)
}
return try {
val upload = uploadCompletableFuture.get()
if (upload != null) {
upload.uploadStatus == UploadStatus.UPLOAD_IN_PROGRESS
} else {
false
}
} catch (e: ExecutionException) {
false
} catch (e: InterruptedException) {
false
}
}
private fun checkConnectivity(connectivityService: ConnectivityService): Boolean {
@@ -340,7 +364,7 @@ class FileUploadHelper {
val uploads = existingFiles.map { file ->
file?.let {
val result = OCUpload(file, user).apply {
OCUpload(file, user).apply {
fileSize = file.fileLength
this.nameCollisionPolicy = nameCollisionPolicy
isCreateRemoteFolder = true
@@ -349,12 +373,9 @@ 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)
}
@@ -438,14 +459,6 @@ class FileUploadHelper {
return false
}
fun showFileUploadLimitMessage(activity: Activity) {
val message = activity.getString(
R.string.file_upload_limit_message,
MAX_FILE_COUNT
)
DisplayUtils.showSnackMessage(activity, message)
}
class UploadNotificationActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val accountName = intent.getStringExtra(FileUploadWorker.EXTRA_ACCOUNT_NAME)
@@ -461,9 +474,7 @@ class FileUploadHelper {
return
}
FileUploadWorker.cancelCurrentUpload(remotePath, accountName, onCompleted = {
instance().updateUploadStatus(remotePath, accountName, UploadStatus.UPLOAD_CANCELLED)
})
instance().cancelFileUpload(remotePath, accountName)
}
}
}
@@ -7,12 +7,10 @@
*/
package com.nextcloud.client.jobs.upload
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.CoroutineWorker
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.nextcloud.client.account.User
import com.nextcloud.client.account.UserAccountManager
@@ -23,12 +21,8 @@ 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
@@ -40,12 +34,8 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode
import com.owncloud.android.lib.common.utils.Log_OC
import com.owncloud.android.operations.UploadFileOperation
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.ErrorMessageAdapter
import com.owncloud.android.utils.theme.ViewThemeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.random.Random
@@ -61,7 +51,7 @@ class FileUploadWorker(
val preferences: AppPreferences,
val context: Context,
params: WorkerParameters
) : CoroutineWorker(context, params),
) : Worker(context, params),
OnDatatransferProgressListener {
companion object {
@@ -101,44 +91,19 @@ class FileUploadWorker(
fun getUploadStartMessage(): String = FileUploadWorker::class.java.name + UPLOAD_START_MESSAGE
fun getUploadFinishMessage(): String = FileUploadWorker::class.java.name + UPLOAD_FINISH_MESSAGE
fun cancelCurrentUpload(remotePath: String, accountName: String, onCompleted: () -> Unit) {
currentUploadFileOperation?.let {
if (it.remotePath == remotePath && it.user.accountName == accountName) {
it.cancel(ResultCode.USER_CANCELLED)
onCompleted()
}
}
}
fun isUploading(remotePath: String?, accountName: String?): Boolean {
currentUploadFileOperation?.let {
return it.remotePath == remotePath && it.user.accountName == accountName
}
return false
}
}
private var lastPercent = 0
private val notificationId = Random.nextInt()
private val notificationManager = UploadNotificationManager(context, viewThemeUtils, notificationId)
private val notificationManager = UploadNotificationManager(context, viewThemeUtils, Random.nextInt())
private val intents = FileUploaderIntents(context)
private val fileUploaderDelegate = FileUploaderDelegate()
@Suppress("TooGenericExceptionCaught")
override suspend fun doWork(): Result = try {
override fun doWork(): Result = try {
Log_OC.d(TAG, "FileUploadWorker started")
val workerName = BackgroundJobManagerImpl.formatClassTag(this::class)
backgroundJobManager.logStartOfWorker(workerName)
val notificationTitle = notificationManager.currentOperationTitle
?: context.getString(R.string.foreground_service_upload)
val notification = createNotification(notificationTitle)
updateForegroundInfo(notification)
backgroundJobManager.logStartOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class))
val result = uploadFiles()
backgroundJobManager.logEndOfWorker(workerName, result)
backgroundJobManager.logEndOfWorker(BackgroundJobManagerImpl.formatClassTag(this::class), result)
notificationManager.dismissNotification()
if (result == Result.success()) {
setIdleWorkerState()
@@ -146,37 +111,17 @@ class FileUploadWorker(
result
} catch (t: Throwable) {
Log_OC.e(TAG, "Error caught at FileUploadWorker $t")
cleanup()
Result.failure()
}
private suspend fun updateForegroundInfo(notification: Notification) {
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
notificationId,
notification,
ForegroundServiceType.DataSync
)
setForeground(foregroundInfo)
}
private fun createNotification(title: String): Notification =
NotificationCompat.Builder(context, NotificationUtils.NOTIFICATION_CHANNEL_UPLOAD)
.setContentTitle(title)
.setSmallIcon(R.drawable.uploads)
.setOngoing(true)
.setSound(null)
.setVibrate(null)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setSilent(true)
.build()
private fun cleanup() {
override fun onStopped() {
Log_OC.e(TAG, "FileUploadWorker stopped")
setIdleWorkerState()
currentUploadFileOperation?.cancel(null)
notificationManager.dismissNotification()
super.onStopped()
}
private fun setWorkerState(user: User?) {
@@ -188,36 +133,36 @@ class FileUploadWorker(
}
@Suppress("ReturnCount", "LongMethod")
private suspend fun uploadFiles(): Result = withContext(Dispatchers.IO) {
private fun uploadFiles(): Result {
val accountName = inputData.getString(ACCOUNT)
if (accountName == null) {
Log_OC.e(TAG, "accountName is null")
return@withContext Result.failure()
return Result.failure()
}
val uploadIds = inputData.getLongArray(UPLOAD_IDS)
if (uploadIds == null) {
Log_OC.e(TAG, "uploadIds is null")
return@withContext Result.failure()
return Result.failure()
}
val currentBatchIndex = inputData.getInt(CURRENT_BATCH_INDEX, -1)
if (currentBatchIndex == -1) {
Log_OC.e(TAG, "currentBatchIndex is -1, cancelling")
return@withContext Result.failure()
return Result.failure()
}
val totalUploadSize = inputData.getInt(TOTAL_UPLOAD_SIZE, -1)
if (totalUploadSize == -1) {
Log_OC.e(TAG, "totalUploadSize is -1, cancelling")
return@withContext Result.failure()
return Result.failure()
}
// since worker's policy is append or replace and account name comes from there no need check in the loop
val optionalUser = userAccountManager.getUser(accountName)
if (!optionalUser.isPresent) {
Log_OC.e(TAG, "User not found for account: $accountName")
return@withContext Result.failure()
return Result.failure()
}
val user = optionalUser.get()
@@ -227,19 +172,21 @@ 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@withContext Result.success()
return Result.success()
}
if (canExitEarly()) {
notificationManager.showConnectionErrorNotification()
return@withContext Result.failure()
return Result.failure()
}
if (isStopped) {
continue
}
setWorkerState(user)
@@ -256,16 +203,12 @@ class FileUploadWorker(
totalUploadSize = totalUploadSize
)
val result = withContext(Dispatchers.IO) {
upload(operation, user, client)
}
val entity = uploadsStorageManager.uploadDao.getUploadById(upload.uploadId, accountName)
uploadsStorageManager.updateStatus(entity, result.isSuccess)
val result = upload(operation, user, client)
currentUploadFileOperation = null
sendUploadFinishEvent(totalUploadSize, currentUploadIndex, operation, result)
}
return@withContext Result.success()
return Result.success()
}
private fun sendUploadFinishEvent(
@@ -403,10 +346,6 @@ class FileUploadWorker(
return
}
if (uploadResult.code == ResultCode.USER_CANCELLED) {
return
}
notificationManager.run {
val errorMessage = ErrorMessageAdapter.getErrorCauseMessage(
uploadResult,
@@ -132,7 +132,6 @@ class WhatsNewActivity :
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
onFinish()
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
@@ -63,12 +63,6 @@ public interface AppPreferences {
boolean isShowHiddenFilesEnabled();
void setShowHiddenFilesEnabled(boolean enabled);
boolean isSortFoldersBeforeFiles();
void setSortFoldersBeforeFiles(boolean enabled);
boolean isSortFavoritesFirst();
void setSortFavoritesFirst(boolean enabled);
boolean isShowEcosystemApps();
void setShowEcosystemApps(boolean enabled);
@@ -70,8 +70,6 @@ public final class AppPreferencesImpl implements AppPreferences {
private static final String PREF__INSTANT_UPLOADING = "instant_uploading";
private static final String PREF__INSTANT_VIDEO_UPLOADING = "instant_video_uploading";
private static final String PREF__SHOW_HIDDEN_FILES = "show_hidden_files_pref";
private static final String PREF__SORT_FOLDERS_BEFORE_FILES = "sort_folders_before_files";
private static final String PREF__SORT_FAVORITES_FIRST = "sort_favorites_first";
private static final String PREF__SHOW_ECOSYSTEM_APPS = "show_ecosystem_apps";
private static final String PREF__LEGACY_CLEAN = "legacyClean";
private static final String PREF__KEYS_MIGRATION = "keysMigration";
@@ -230,26 +228,6 @@ public final class AppPreferencesImpl implements AppPreferences {
preferences.edit().putBoolean(PREF__SHOW_HIDDEN_FILES, enabled).apply();
}
@Override
public boolean isSortFoldersBeforeFiles() {
return preferences.getBoolean(PREF__SORT_FOLDERS_BEFORE_FILES, true);
}
@Override
public void setSortFoldersBeforeFiles(boolean enabled) {
preferences.edit().putBoolean(PREF__SORT_FOLDERS_BEFORE_FILES, enabled).apply();
}
@Override
public boolean isSortFavoritesFirst() {
return preferences.getBoolean(PREF__SORT_FAVORITES_FIRST, true);
}
@Override
public void setSortFavoritesFirst(boolean enabled) {
preferences.edit().putBoolean(PREF__SORT_FAVORITES_FIRST, enabled).apply();
}
@Override
public boolean isShowEcosystemApps() {
return preferences.getBoolean(PREF__SHOW_ECOSYSTEM_APPS, true);
@@ -84,7 +84,6 @@ class ChooseAccountDialogFragment :
return builder.create()
}
@Suppress("LongMethod")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
accountManager = (activity as BaseActivity).userAccountManager
@@ -39,8 +39,8 @@ enum class FileAction(
// Uploads and downloads
DOWNLOAD_FILE(R.id.action_download_file, R.string.filedetails_download, R.drawable.ic_cloud_download),
DOWNLOAD_FOLDER(R.id.action_sync_file, R.string.filedetails_sync_file, R.drawable.ic_sync),
CANCEL_SYNC(R.id.action_cancel_sync, R.string.common_cancel_sync, R.drawable.ic_sync_off),
SYNC_FILE(R.id.action_sync_file, R.string.filedetails_sync_file, R.drawable.ic_cloud_sync_on),
CANCEL_SYNC(R.id.action_cancel_sync, R.string.common_cancel_sync, R.drawable.ic_cloud_sync_off),
// File sharing
EXPORT_FILE(R.id.action_export_file, R.string.filedetails_export, R.drawable.ic_export),
@@ -84,7 +84,7 @@ enum class FileAction(
SEND_SHARE_FILE,
SEND_FILE,
OPEN_FILE_WITH,
DOWNLOAD_FOLDER,
SYNC_FILE,
CANCEL_SYNC,
SELECT_ALL,
SELECT_NONE,
@@ -8,10 +8,7 @@
package com.nextcloud.utils
import android.graphics.Bitmap
import android.graphics.Matrix
import androidx.core.graphics.scale
import androidx.exifinterface.media.ExifInterface
import com.owncloud.android.lib.common.utils.Log_OC
@Suppress("MagicNumber")
fun Bitmap.allocationKilobyte(): Int = allocationByteCount.div(1024)
@@ -41,79 +38,3 @@ fun Bitmap.scaleUntil(targetKB: Int): Bitmap {
val scaledBitmap = scale(width, height)
return scaledBitmap.scaleUntil(targetKB)
}
/**
* Rotates and/or flips a [Bitmap] according to an EXIF orientation constant.
*
* Needed because loading bitmaps directly may ignore EXIF metadata with some devices,
* resulting in incorrectly displayed images.
*
* This function uses a [Matrix] transformation to adjust the image so that it
* appears upright when displayed. It supports all standard EXIF orientations,
* including mirrored and rotated cases.
*
* The original bitmap will be recycled if a new one is successfully created.
* If the device runs out of memory during the transformation, the original bitmap
* is returned unchanged.
*
* @receiver The [Bitmap] to rotate or flip. Can be `null`.
* @param orientation One of the [ExifInterface] orientation constants, such as
* [ExifInterface.ORIENTATION_ROTATE_90] or [ExifInterface.ORIENTATION_FLIP_HORIZONTAL].
* @return The correctly oriented [Bitmap], or `null` if the receiver was `null`.
*
* @see ExifInterface
* @see Matrix
*/
@Suppress("MagicNumber", "ReturnCount")
fun Bitmap?.rotateBitmapViaExif(orientation: Int): Bitmap? {
if (this == null) {
return null
}
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return this
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return this
}
return try {
val rotated = Bitmap.createBitmap(
this,
0,
0,
this.width,
this.height,
matrix,
true
)
// release original if a new one was created
if (rotated != this) {
this.recycle()
}
rotated
} catch (_: OutOfMemoryError) {
Log_OC.e("BitmapExtension", "rotating bitmap, out of memory exception")
this
}
}
@@ -1,67 +0,0 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[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,62 +45,52 @@ class ShortcutUtil @Inject constructor(private val mContext: Context) {
user: User,
syncedFolderProvider: SyncedFolderProvider
) {
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 -> {
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) {
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)
IconCompat.createWithBitmap(drawable.toBitmap())
val bitmapIcon = drawable.toBitmap()
icon = IconCompat.createWithBitmap(bitmapIcon)
} else {
icon = IconCompat.createWithResource(
mContext,
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
)
}
else -> IconCompat.createWithResource(
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(
mContext,
MimeTypeUtil.getFileTypeIconId(file.mimeType, file.fileName)
0,
pinnedShortcutCallbackIntent,
FLAG_IMMUTABLE
)
ShortcutManagerCompat.requestPinShortcut(
mContext,
pinShortcutInfo,
successCallback.intentSender
)
}
}
@@ -1,7 +1,7 @@
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2025 Alper Ozturk <[email protected]>
* SPDX-FileCopyrightText: 2024 Alper Ozturk <[email protected]>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
@@ -10,10 +10,22 @@ 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
fun DrawerActivity.navigateToAllFiles() {
@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
}
DrawerActivity.menuItemId = R.id.nav_all_files
setNavigationViewItemChecked()
@@ -26,4 +38,6 @@ fun DrawerActivity.navigateToAllFiles() {
}.run {
startActivity(this)
}
return true
}
@@ -15,6 +15,9 @@ 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,10 +7,6 @@
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
@@ -29,27 +25,3 @@ 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
}
}
@@ -1,77 +0,0 @@
/*
* 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
}
@@ -1,28 +0,0 @@
/*
* 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)
@@ -1,43 +0,0 @@
/*
* 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.startAutoUploadImmediately(syncedFolderProvider, backgroundJobManager, false);
FilesSyncHelper.startFilesSyncForAllFolders(syncedFolderProvider, backgroundJobManager,false, new String[]{});
preferences.setAutoUploadInit(true);
}
@@ -706,13 +706,6 @@ 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,10 +10,7 @@
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;
@@ -108,7 +105,7 @@ public class SyncedFolder implements Serializable, Cloneable {
*
* @param id id
*/
public SyncedFolder(long id,
protected SyncedFolder(long id,
String localPath,
String remotePath,
boolean wifiOnly,
@@ -279,20 +276,15 @@ public class SyncedFolder implements Serializable, Cloneable {
this.excludeHidden = excludeHidden;
}
public boolean containsTypedFile(File file,String filePath){
public boolean containsTypedFile(String filePath){
boolean isCorrectMediaType =
(getType() == MediaFolderType.IMAGE && MimeTypeUtil.isImage(file)) ||
(getType() == MediaFolderType.VIDEO && MimeTypeUtil.isVideo(file)) ||
getType() == MediaFolderType.CUSTOM;
(getType() == MediaFolderType.IMAGE && MimeTypeUtil.isImage(new File(filePath))) ||
(getType() == MediaFolderType.VIDEO && MimeTypeUtil.isVideo(new File(filePath))) ||
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,14 +15,9 @@ 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;
@@ -47,7 +42,6 @@ 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.
@@ -189,11 +183,33 @@ public class SyncedFolderProvider extends Observable {
}
public SyncedFolder findByLocalPathAndAccount(String localPath, User user) {
final SyncedFolderEntity entity = dao.findByLocalPathAndAccount(localPath, user.getAccountName());
if (entity == null) {
return null;
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.");
}
}
return SyncedFolderEntityKt.toSyncedFolder(entity);
if (cursor != null) {
cursor.close();
}
return result;
}
@Nullable
@@ -37,7 +37,6 @@ 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;
@@ -78,8 +77,6 @@ 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.
*/
@@ -197,8 +194,7 @@ public final class ThumbnailsCacheManager {
Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
// Rotate image, obeying exif tag
int orientation = getExifOrientation(path);
thumbnail = BitmapExtensionsKt.rotateBitmapViaExif(thumbnail, orientation);
thumbnail = BitmapUtils.rotateImage(thumbnail,path);
// Add thumbnail to cache
// do not overwrite any pre-existing image
@@ -1,7 +1,6 @@
/*
* 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]>
@@ -15,9 +14,14 @@
*/
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;
@@ -90,6 +94,97 @@ 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.
*
@@ -292,6 +387,52 @@ 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;
@@ -367,6 +508,19 @@ 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<>();
@@ -476,6 +630,17 @@ 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()
@@ -505,6 +670,13 @@ 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();
@@ -512,6 +684,22 @@ 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;
}
@@ -609,7 +797,7 @@ public class UploadsStorageManager extends Observable {
upload.getRemotePath(),
localPath
);
} else if (uploadResult.getCode() != RemoteOperationResult.ResultCode.USER_CANCELLED){
} else {
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(file.getRemotePath(), user.getAccountName())) {
if (FileUploadHelper.Companion.instance().isUploading(user, file)) {
return true;
}
}
@@ -25,9 +25,6 @@ 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.
@@ -164,32 +161,26 @@ public class RenameFileOperation extends SyncOperation {
}
// create a test file
String tmpFolderName = FileStorageUtils.getTemporalPath("");
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());
}
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());
}
if (tmpFolder != null && !Files.isDirectory(tmpFolder)) {
if (!tmpFolder.isDirectory()) {
throw new IOException("Unexpected error: temporal directory could not be created");
}
try {
Files.createFile(testFile);
} catch (Exception e) {
testFile.createNewFile(); // return value is ignored; it could be 'false' because
// the file already existed, that doesn't invalidate the name
} catch (IOException e) {
Log_OC.i(TAG, "Test for validity of name " + newName + " in the file system failed");
return false;
}
boolean result = Files.exists(testFile) && Files.isRegularFile(testFile);
boolean result = testFile.exists() && testFile.isFile();
try {
Files.deleteIfExists(testFile);
} catch (Exception e) {
Log_OC.e("Error deleting file: ", e.getMessage());
return true;
}
// cleaning ; result is ignored, since there is not much we could do in case of failure,
// but repeat and repeat...
testFile.delete();
return result;
}
@@ -28,6 +28,7 @@ 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;
@@ -484,7 +485,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
Log_OC.d(TAG, "Exception caught at startDirectDownloads" + e);
}
} else {
fileDownloadHelper.downloadFolder(mLocalFolder, user.getAccountName());
mFilesForDirectDownload.forEach(file -> fileDownloadHelper.downloadFile(user, file));
}
}
@@ -79,11 +79,12 @@ 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;
@@ -244,7 +245,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;
@@ -970,14 +971,11 @@ 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;
}
@@ -985,7 +983,6 @@ public class UploadFileOperation extends SyncOperation {
// check name collision
final var collisionResult = checkNameCollision(null, client, null, false);
if (collisionResult != null) {
result = collisionResult;
return collisionResult;
}
@@ -997,19 +994,73 @@ public class UploadFileOperation extends SyncOperation {
return result;
}
// Get the last modification date of the file from the file system
// Get timestamps
long lastModifiedTimestamp = originalFile.lastModified() / 1000;
final Long creationTimestamp = FileUtil.getCreationTimestamp(originalFile);
try {
channel = new RandomAccessFile(mFile.getStoragePath(), "rw").getChannel();
try (RandomAccessFile raf = new RandomAccessFile(mFile.getStoragePath(), "rw");
FileChannel channel = raf.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) {
// 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();
// Handle SD card case (copy to temp dir, lock there)
String temporalPath = FileStorageUtils.getInternalTemporalPath(user.getAccountName(), mContext)
+ mFile.getRemotePath();
mFile.setStoragePath(temporalPath);
temporalFile = new File(temporalPath);
@@ -1018,66 +1069,16 @@ public class UploadFileOperation extends SyncOperation {
if (result.isSuccess()) {
if (temporalFile.length() == originalFile.length()) {
channel = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw").getChannel();
fileLock = channel.tryLock();
try (RandomAccessFile raf = new RandomAccessFile(temporalFile.getAbsolutePath(), "rw");
FileChannel channel = raf.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);
@@ -1097,14 +1098,7 @@ public class UploadFileOperation extends SyncOperation {
}
}
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
Log_OC.w(TAG, "Failed to close file channel");
}
}
// delete temporal file
if (temporalFile != null && !originalFile.equals(temporalFile)) {
boolean isTempFileDeleted = temporalFile.delete();
Log_OC.d(TAG, "normalUpload, temp folder deletion: " + isTempFileDeleted);
@@ -1123,7 +1117,6 @@ 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());
}
@@ -1434,37 +1427,21 @@ public class UploadFileOperation extends SyncOperation {
}
/**
* 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
* 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.
*/
public void cancel(ResultCode cancellationReason) {
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 (mUploadOperation == null) {
if (mUploadStarted.get()) {
Log_OC.d(TAG, "Cancelling upload during preparation.");
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 {
Log_OC.d(TAG, "Cancelling upload during actual upload operation.");
mUploadOperation.cancel(cancellationReason);
}
}
@@ -1575,8 +1552,10 @@ public class UploadFileOperation extends SyncOperation {
// try to copy and then delete
Files.createFile(targetFile.toPath());
try (
FileChannel inChannel = new FileInputStream(sourceFile).getChannel();
FileChannel outChannel = new FileOutputStream(targetFile).getChannel()
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(targetFile);
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.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_sync_off);
binding.emptyList.emptyListIcon.setImageResource(R.drawable.ic_cloud_sync_off);
}
});
@@ -31,7 +31,6 @@ 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;
@@ -116,7 +115,6 @@ import java.util.Optional;
import javax.inject.Inject;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
@@ -208,12 +206,6 @@ 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.
*/
@@ -1161,24 +1153,19 @@ public abstract class DrawerActivity extends ToolbarActivity
}
}
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
public void onBackPressed() {
if (isDrawerOpen()) {
closeDrawer();
return;
}
Fragment fileDetailsSharingProcessFragment =
getSupportFragmentManager().findFragmentByTag(FileDetailsSharingProcessFragment.TAG);
if (fileDetailsSharingProcessFragment != null) {
((FileDetailsSharingProcessFragment) fileDetailsSharingProcessFragment).onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
@@ -129,7 +129,6 @@ 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,7 +40,6 @@ 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
@@ -83,7 +82,6 @@ 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
@@ -157,6 +155,7 @@ 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
@@ -279,7 +278,6 @@ class FileDisplayActivity :
initSyncBroadcastReceiver()
observeWorkerState()
startMetadataSyncForRoot()
handleBackPress()
}
private fun loadSavedInstanceState(savedInstanceState: Bundle?) {
@@ -551,7 +549,7 @@ class FileDisplayActivity :
when {
ACTION_DETAILS.equals(action, ignoreCase = true) -> {
val file = getFileFromIntent(intent)
val file = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
setFile(file)
showDetails(file)
}
@@ -580,6 +578,7 @@ class FileDisplayActivity :
when (intent.action) {
Intent.ACTION_VIEW -> handleOpenFileViaIntent(intent)
OPEN_FILE -> {
supportFragmentManager.executePendingTransactions()
onOpenFileIntent(intent)
}
}
@@ -646,41 +645,18 @@ class FileDisplayActivity :
// endregion
private fun onOpenFileIntent(intent: Intent) {
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
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
}
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)
fileFragment.onItemClicked(file)
}
}
@@ -959,7 +935,7 @@ class FileDisplayActivity :
) {
openDrawer()
} else {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
}
} else if (itemId == R.id.action_select_all) {
val fragment = this.listOfFilesFragment
@@ -1160,59 +1136,40 @@ class FileDisplayActivity :
}
}
/**
* 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.
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()
*/
private fun handleBackPress() {
onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
when {
isSearchOpen() -> {
isEnabled = false
resetSearchAction()
}
@SuppressFBWarnings("ITC_INHERITANCE_TYPE_CHECKING") // TODO Apply fail fast principle
override fun onBackPressed() {
if (isSearchOpen()) {
resetSearchAction()
return
}
isDrawerOpen -> {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
if (isDrawerOpen) {
super.onBackPressed()
return
}
leftFragment is OCFileListFragment -> {
val fragment = leftFragment as OCFileListFragment
if (isRoot(getCurrentDir())) {
if (fragment.shouldNavigateBackToAllFiles()) {
navigateToAllFiles()
} else {
finish()
}
} else {
browseUp(fragment)
}
}
else -> {
isEnabled = false
popBack()
}
}
}
if (this.leftFragment is OCFileListFragment) {
if (isRoot(getCurrentDir())) {
finish()
} else {
browseUp(leftFragment as OCFileListFragment)
}
)
} else {
popBack()
}
}
private fun browseUp(listOfFiles: OCFileListFragment) {
@@ -1243,10 +1200,9 @@ class FileDisplayActivity :
if (isRoot(getCurrentDir()) && leftFragment is OCFileListFragment) {
// Remove the list to the original state
leftFragment.adapter?.let { adapter ->
val listOfHiddenFiles = adapter.listOfHiddenFiles
leftFragment.performSearch("", listOfHiddenFiles, true)
}
val listOfHiddenFiles = leftFragment.adapter.listOfHiddenFiles
leftFragment.performSearch("", listOfHiddenFiles, true)
hideSearchView(getCurrentDir())
setDrawerIndicatorEnabled(isDrawerIndicatorAvailable)
@@ -1254,20 +1210,20 @@ class FileDisplayActivity :
if (leftFragment is UnifiedSearchFragment) {
showSortListGroup(false)
onBackPressedDispatcher.onBackPressed()
super.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 onBackPressedDispatcher.onBackPressed()
* [with false][.showSortListGroup]. At last call to super.onBackPressed()
*/
private fun popBack() {
binding.fabMain.setImageResource(R.drawable.ic_plus)
resetScrolling(true)
showSortListGroup(false)
onBackPressedDispatcher.onBackPressed()
super.onBackPressed()
}
override fun onSaveInstanceState(outState: Bundle) {
@@ -1313,8 +1269,11 @@ class FileDisplayActivity :
var startFile: OCFile? = null
if (intent != null) {
startFile = getFileFromIntent(intent)
file = startFile
val fileArgs = intent.getParcelableArgument(EXTRA_FILE, OCFile::class.java)
if (fileArgs != null) {
startFile = fileArgs
file = startFile
}
}
// refresh list of files
@@ -1355,11 +1314,6 @@ 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
@@ -1691,7 +1645,7 @@ class FileDisplayActivity :
if (uploadWasFine || file != null && file.fileExists()) {
fileDetailFragment.updateFileDetails(false, true)
} else {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
}
// Force the preview if the file is an image or text file
@@ -106,7 +106,7 @@ open class FolderPickerActivity :
updateActionBarTitleAndHomeButtonByString(captionText)
setBackgroundText()
handleBackPress()
handleOnBackPressed()
}
override fun onDestroy() {
@@ -151,7 +151,7 @@ open class FolderPickerActivity :
}
}
private fun handleBackPress() {
private fun handleOnBackPressed() {
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) {
onBackPressedDispatcher.onBackPressed()
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 -> {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
}
R.id.action_dismiss_two_way_sync -> {
disableTwoWaySyncAndWorkers()
@@ -91,7 +91,7 @@ class ManageAccountsActivity :
multipleAccountsSupported = multiAccountSupport(this)
setupUserList()
handleBackPress()
handleOnBackPressed()
}
private fun setupUsers() {
@@ -149,7 +149,7 @@ class ManageAccountsActivity :
performAccountRemoval(user)
}
private fun handleBackPress() {
private fun handleOnBackPressed() {
onBackPressedDispatcher.addCallback(
this,
onBackPressedCallback
@@ -160,13 +160,13 @@ class ManageAccountsActivity :
override fun handleOnBackPressed() {
val resultIntent = Intent()
if (accountManager.allUsers.isNotEmpty()) {
if (accountManager.allUsers.size > 0) {
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.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
@@ -229,7 +229,7 @@ class ManageAccountsActivity :
var result = true
if (item.itemId == android.R.id.home) {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
} else {
result = super.onOptionsItemSelected(item)
}
@@ -331,7 +331,7 @@ class ManageAccountsActivity :
)
recyclerView?.adapter = userListAdapter
} else {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
}
}
@@ -393,7 +393,8 @@ class ManageAccountsActivity :
resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, true)
resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, true)
setResult(RESULT_OK, resultIntent)
onBackPressedDispatcher.onBackPressed()
super.onBackPressed()
}
}
@@ -103,7 +103,6 @@ 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;
@@ -204,8 +203,6 @@ 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
@@ -659,19 +656,14 @@ public class ReceiveExternalFilesActivity extends FileActivity
}
}
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
public void onBackPressed() {
if (mParents.size() <= SINGLE_PARENT) {
super.onBackPressed();
} else {
mParents.pop();
browseToFolderIfItExists();
}
}
@Override
@@ -882,9 +874,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
private List<OCFile> sortFileList(List<OCFile> files) {
FileSortOrder sortOrder = preferences.getSortOrderByFolder(mFile);
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
boolean favoritesFirst = preferences.isSortFavoritesFirst();
return sortOrder.sortCloudFiles(files, foldersBeforeFiles, favoritesFirst);
return sortOrder.sortCloudFiles(files);
}
private String generatePath(Stack<String> dirs) {
@@ -954,7 +944,7 @@ public class ReceiveExternalFilesActivity extends FileActivity
}
if (mStreamsToUpload.size() > FileUploadHelper.MAX_FILE_COUNT) {
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
return;
}
@@ -1107,7 +1097,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) {
getOnBackPressedDispatcher().onBackPressed();
onBackPressed();
}
} else if (itemId == R.id.action_switch_account) {
showAccountChooserDialog();
@@ -15,7 +15,6 @@
*/
package com.owncloud.android.ui.activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
@@ -184,9 +183,6 @@ public class SettingsActivity extends PreferenceActivity
// Synced folders
setupAutoUploadCategory(preferenceScreen);
// Files
setupFilesCategory();
// Details
setupDetailsCategory(preferenceScreen);
@@ -358,7 +354,6 @@ public class SettingsActivity extends PreferenceActivity
}
}
@SuppressLint("GestureBackNavigation")
@Override
public void onBackPressed() {
DrawerActivity.menuItemId = R.id.nav_all_files;
@@ -666,33 +661,25 @@ 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 && fSyncedFolderLightEnabled
if (!fPassCodeEnabled && !fDeviceCredentialsEnabled && !fShowHiddenFilesEnabled && 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 =
@@ -716,22 +703,6 @@ 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,7 +28,6 @@ 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
@@ -147,9 +146,6 @@ class SyncedFoldersActivity :
@Inject
lateinit var syncedFolderProvider: SyncedFolderProvider
@Inject
lateinit var appInfo: AppInfo
lateinit var binding: SyncedFoldersLayoutBinding
lateinit var adapter: SyncedFolderAdapter
@@ -235,8 +231,7 @@ class SyncedFoldersActivity :
this,
lightVersion,
viewThemeUtils,
powerManagementService,
connectivityService
powerManagementService
)
binding.emptyList.emptyListIcon.setImageResource(R.drawable.nav_synced_folders)
viewThemeUtils.material.colorMaterialButtonPrimaryFilled(binding.emptyList.emptyListViewAction)
@@ -566,7 +561,7 @@ class SyncedFoldersActivity :
}
}
if (syncedFolderDisplayItem.isEnabled) {
backgroundJobManager.startAutoUploadImmediately(syncedFolderDisplayItem, overridePowerSaving = false)
backgroundJobManager.startImmediateFilesSyncJob(syncedFolderDisplayItem, overridePowerSaving = false)
showBatteryOptimizationInfo()
}
}
@@ -729,7 +724,7 @@ class SyncedFoldersActivity :
// existing synced folder setup to be updated
syncedFolderProvider.updateSyncFolder(item)
if (item.isEnabled) {
backgroundJobManager.startAutoUploadImmediately(item, overridePowerSaving = false)
backgroundJobManager.startImmediateFilesSyncJob(item, overridePowerSaving = false)
} else {
val syncedFolderInitiatedKey = KEY_SYNCED_FOLDER_INITIATED_PREFIX + item.id
val arbitraryDataProvider =
@@ -746,7 +741,7 @@ class SyncedFoldersActivity :
if (storedId != -1L) {
item.id = storedId
if (item.isEnabled) {
backgroundJobManager.startAutoUploadImmediately(item, overridePowerSaving = false)
backgroundJobManager.startImmediateFilesSyncJob(item, overridePowerSaving = false)
} else {
val syncedFolderInitiatedKey = KEY_SYNCED_FOLDER_INITIATED_PREFIX + item.id
arbitraryDataProvider.deleteKeyForAccount("global", syncedFolderInitiatedKey)
@@ -862,7 +857,7 @@ class SyncedFoldersActivity :
val powerManager = getSystemService(POWER_SERVICE) as PowerManager?
return when {
powerManager != null -> !powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID)
else -> !appInfo.isDebugBuild
else -> true
}
}
}
@@ -157,32 +157,17 @@ 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);
String title = getActionBarTitle(chosenFile, isRoot);
title = isRoot ? themeUtils.getDefaultDisplayNameForRootFolder(this) : fileDataStorageManager.getFilenameConsideringOfflineOperation(chosenFile);
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);
@@ -287,21 +272,11 @@ public abstract class ToolbarActivity extends BaseActivity implements Injectable
}
public void showSortListGroup(boolean show) {
final var view = findViewById(R.id.sort_list_button_group);
if (view == null) {
return;
}
view.setVisibility(show ? View.VISIBLE : View.GONE);
findViewById(R.id.sort_list_button_group).setVisibility(show ? View.VISIBLE : View.GONE);
}
public boolean sortListGroupVisibility(){
final var view = findViewById(R.id.sort_list_button_group);
if (view == null) {
return false;
}
return view.getVisibility() == View.VISIBLE;
return findViewById(R.id.sort_list_button_group).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) {
getOnBackPressedDispatcher().onBackPressed();
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) {
getOnBackPressedDispatcher().onBackPressed();
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) {
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
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) {
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
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) {
FileUploadHelper.Companion.instance().showFileUploadLimitMessage(this);
DisplayUtils.showSnackMessage(this, R.string.max_file_count_warning_message);
return;
}
@@ -182,9 +182,10 @@ public class UploadListActivity extends FileActivity {
}
private void refresh() {
FilesSyncHelper.startAutoUploadImmediately(syncedFolderProvider,
FilesSyncHelper.startFilesSyncForAllFolders(syncedFolderProvider,
backgroundJobManager,
true);
true,
new String[]{});
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) {
getOnBackPressedDispatcher().onBackPressed();
onBackPressed();
} else if (itemId == R.id.action_open_account) {
accountClicked(user.hashCode());
} else if (itemId == R.id.action_delete_account) {
@@ -9,7 +9,6 @@
*/
package com.owncloud.android.ui.adapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
@@ -24,7 +23,6 @@ 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;
@@ -36,6 +34,8 @@ 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,10 +69,8 @@ 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,
@@ -85,9 +83,15 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
checkedFiles = new HashSet<>();
this.viewThemeUtils = viewThemeUtils;
this.isWithinEncryptedFolder = isWithinEncryptedFolder;
setHasStableIds(true);
swapDirectory(directory);
}
@Override
public int getItemCount() {
return mFiles.size() + 1;
}
public int getFilesCount() {
return mFiles.size();
}
@@ -125,39 +129,30 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
}
public String[] getCheckedFilesPath() {
List<String> result = FileHelper.INSTANCE.listFilesRecursive(checkedFiles);
List<String> result = listFilesRecursive(checkedFiles);
Log_OC.d(TAG, "Returning " + result.size() + " selected files");
return result.toArray(new String[0]);
}
@Override
public int getItemCount() {
return mFiles.size() + 1;
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 long getItemId(int position) {
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;
}
}
return mFiles.size() <= position ? position : -1;
}
@Override
@@ -276,6 +271,19 @@ 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);
}
@@ -309,81 +317,43 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
*/
public void swapDirectory(final File directory) {
localFileListFragmentInterface.setLoading(true);
currentOffset = 0;
mFiles.clear();
mFilesAll.clear();
final Handler uiHandler = new Handler(Looper.getMainLooper());
Executors.newSingleThreadExecutor().execute(() -> {
// Load first page of folders
List<File> firstPage = FileHelper.INSTANCE.listDirectoryEntries(directory, currentOffset, PAGE_SIZE, true);
if (!firstPage.isEmpty()) {
firstPage = sortAndFilterHiddenEntries(firstPage);
List<File> fileList;
if (directory == null) {
fileList = new ArrayList<>();
} else {
if (mLocalFolderPicker) {
fileList = getFolders(directory);
} else {
fileList = getFiles(directory);
}
}
currentOffset += PAGE_SIZE;
updateUIForFirstPage(firstPage);
if (!fileList.isEmpty()) {
FileSortOrder sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.localFileListView);
fileList = sortOrder.sortLocalFiles(fileList);
// Load remaining folders, then all files
loadRemainingEntries(directory, true);
// Reset for files
currentOffset = 0;
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;
// Fetch preferences for showing hidden files
boolean showHiddenFiles = preferences.isShowHiddenFilesEnabled();
if (!showHiddenFiles) {
fileList = filterHiddenFiles(fileList);
}
}
final List<File> newFiles = fileList;
nextPage = sortAndFilterHiddenEntries(nextPage);
uiHandler.post(() -> {
mFiles = newFiles;
mFilesAll = new ArrayList<>();
mFilesAll.addAll(mFiles);
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);
notifyDataSetChanged();
localFileListFragmentInterface.setLoading(false);
});
});
}
@SuppressLint("NotifyDataSetChanged")
public void setSortOrder(FileSortOrder sortOrder) {
localFileListFragmentInterface.setLoading(true);
final Handler uiHandler = new Handler(Looper.getMainLooper());
@@ -396,9 +366,30 @@ 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;
@@ -523,11 +514,11 @@ public class LocalFileListAdapter extends RecyclerView.Adapter<RecyclerView.View
}
}
@SuppressLint("NotifyDataSetChanged")
@VisibleForTesting
public void setFiles(List<File> newFiles) {
mFiles = newFiles;
mFilesAll = new ArrayList<>(mFiles);
mFilesAll = new ArrayList<>();
mFilesAll.addAll(mFiles);
notifyDataSetChanged();
localFileListFragmentInterface.setLoading(false);
@@ -266,9 +266,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
if (searchType == SearchType.SHARED_FILTER) {
mFiles.sort((o1, o2) -> Long.compare(o2.getFirstShareTimestamp(), o1.getFirstShareTimestamp()));
} else {
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
boolean favoritesFirst = preferences.isSortFavoritesFirst();
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
mFiles = sortOrder.sortCloudFiles(mFiles);
}
new Handler(Looper.getMainLooper()).post(() -> {
@@ -909,9 +907,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
mFiles = OCFileExtensionsKt.filterFilenames(mFiles);
sortOrder = preferences.getSortOrderByFolder(directory);
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
boolean favoritesFirst = preferences.isSortFavoritesFirst();
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
mFiles = sortOrder.sortCloudFiles(mFiles);
prepareListOfHiddenFiles();
mergeOCFilesForLivePhoto();
mFilesAll.clear();
@@ -1003,18 +999,15 @@ 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, foldersBeforeFiles, favoritesFirst);
mFiles = sortOrder.sortCloudFiles(mFiles);
}
this.searchType = searchType;
mFilesAll.clear();
mFilesAll.addAll(mFiles);
@@ -1141,17 +1134,14 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
mStorageManager.saveVirtuals(contentValues);
}
@SuppressLint("NotifyDataSetChanged")
public void setSortOrder(@Nullable OCFile folder, @NonNull FileSortOrder sortOrder) {
public void setSortOrder(@Nullable OCFile folder, FileSortOrder sortOrder) {
if (searchType == SearchType.FAVORITE_SEARCH) {
preferences.setSortOrder(FileSortOrder.Type.favoritesListView, sortOrder);
} else {
preferences.setSortOrder(folder, sortOrder);
}
boolean foldersBeforeFiles = preferences.isSortFoldersBeforeFiles();
boolean favoritesFirst = preferences.isSortFavoritesFirst();
mFiles = sortOrder.sortCloudFiles(mFiles, foldersBeforeFiles, favoritesFirst);
mFiles = sortOrder.sortCloudFiles(mFiles);
notifyDataSetChanged();
this.sortOrder = sortOrder;
@@ -380,7 +380,7 @@ class OCFileListDelegate(
return operationsServiceBinder?.isSynchronizing(user, file) == true ||
fileDownloadHelper.isDownloading(user, file) ||
fileUploadHelper.isUploading(file.remotePath, user.accountName)
fileUploadHelper.isUploading(user, file)
}
private fun showLocalFileIndicator(file: OCFile, holder: ListViewHolder) {
@@ -23,8 +23,6 @@ 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
@@ -34,7 +32,6 @@ 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
@@ -44,7 +41,6 @@ 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.
@@ -57,8 +53,7 @@ class SyncedFolderAdapter(
private val clickListener: ClickListener,
private val light: Boolean,
private val viewThemeUtils: ViewThemeUtils,
private val powerManagementService: PowerManagementService,
private val connectivityService: ConnectivityService
private val powerManagementService: PowerManagementService
) : SectionedRecyclerViewAdapter<SectionedViewHolder>() {
private val gridTotal = gridWidth * 2
@@ -67,14 +62,6 @@ 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)
@@ -250,112 +237,58 @@ 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
holder.binding.run {
headerContainer.visibility = View.VISIBLE
if (section == 0) {
autoUploadBatterySaverWarningCard.root.run {
setVisibleIf(powerManagementService.isPowerSavingEnabled)
viewThemeUtils.material.themeCardView(this)
}
if (section == 0) {
holder.binding.autoUploadBatterySaverWarningCard.root.run {
setVisibleIf(powerManagementService.isPowerSavingEnabled)
viewThemeUtils.material.themeCardView(this)
}
val syncedFolder = filteredSyncFolderItems[section]
title.text = syncedFolder.folderName
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)
}
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)
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.title.text = filteredSyncFolderItems[section].folderName
holder.binding.scanIndicatorText.setVisibleIf(syncedFolder.isEnabled && (scanIndicatorText != null))
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)
}
if (holder.binding.scanIndicatorText.isVisible) {
setMaxWidthOfScanIndicatorText(holder)
holder.binding.scanIndicatorText.text = scanIndicatorText
} else {
setBottomMarginOfTitle(holder)
}
}
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)
private fun setMaxWidthOfScanIndicatorText(holder: HeaderViewHolder) {
var visibleTrailingIconCount = 2
if (holder.binding.subFolderWarningButton.isVisible) {
visibleTrailingIconCount += 1
}
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
)
}
}
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)
initSubFolderWarningButton(holder, section)
}
}
@@ -8,7 +8,6 @@
*/
package com.owncloud.android.ui.adapter;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
@@ -60,7 +59,6 @@ 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;
@@ -69,7 +67,6 @@ 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.
@@ -77,18 +74,6 @@ import kotlin.Unit;
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;
@@ -108,66 +93,6 @@ 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;
@@ -219,10 +144,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
return;
}
for (OCUpload upload: group.items) {
uploadHelper.updateUploadStatus(upload.getRemotePath(), accountName, UploadStatus.UPLOAD_CANCELLED);
FileUploadWorker.Companion.cancelCurrentUpload(upload.getRemotePath(), accountName, () -> Unit.INSTANCE);
}
uploadHelper.cancelFileUploads(Arrays.asList(group.items), accountName);
loadUploadItemsFromDb();
}).start();
case FINISHED -> {
@@ -320,6 +242,66 @@ 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) {
@@ -445,8 +427,7 @@ 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.updateUploadStatus(item.getRemotePath(), item.getAccountName(), UploadStatus.UPLOAD_CANCELLED);
FileUploadWorker.Companion.cancelCurrentUpload(item.getRemotePath(), item.getAccountName(), () -> Unit.INSTANCE);
uploadHelper.cancelFileUpload(item.getRemotePath(), item.getAccountName());
loadUploadItemsFromDb();
});
@@ -933,7 +914,7 @@ public class UploadListAdapter extends SectionedRecyclerViewAdapter<SectionedVie
}
interface Refresh {
void refresh(LoadCompleteListener listener);
void refresh();
}
interface Apply {
@@ -1012,30 +993,20 @@ 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(() -> {
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();
}
});
}
}
});
group.refresh();
}
parentActivity.runOnUiThread(() -> {
for (UploadGroup uploadGroup : uploadGroups) {
uploadGroup.apply();
}
notifyDataSetChanged();
for (LoadCompleteListener loadCompleteListener : loadCompleteListenerSet) {
loadCompleteListener.onComplete();
}
});
}
}
@@ -28,8 +28,6 @@ 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;
@@ -58,67 +56,69 @@ 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) return Boolean.FALSE;
if (file.exists() && !file.delete()) return Boolean.FALSE;
File parentFile = file.getParentFile();
if (parentFile == null) 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());
FileOutputStream fos = new FileOutputStream(file)
) {
byte[] buffer = new byte[4096];
long transferred = 0;
int read;
while ((read = bis.read(buffer)) != -1) {
fos.write(buffer, 0, read);
transferred += read;
}
if (totalToTransfer > 0 && transferred != totalToTransfer) {
Log_OC.d(TAG, "Transferred bytes (" + transferred +
") != expected (" + totalToTransfer + ")");
if (status == HttpStatus.SC_OK) {
if (file.exists() && !file.delete()) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
} catch (Exception e) {
Log_OC.e(TAG, "Error downloading file", e);
return Boolean.FALSE;
file.getParentFile().mkdirs();
if (!file.getParentFile().exists()) {
Log_OC.d(TAG, file.getParentFile().getAbsolutePath() + " does not exist");
return Boolean.FALSE;
}
if (!file.createNewFile()) {
Log_OC.d(TAG, file.getAbsolutePath() + " could not be created");
return Boolean.FALSE;
}
BufferedInputStream bis = new BufferedInputStream(getMethod.getResponseBodyAsStream());
fos = new FileOutputStream(file);
long transferred = 0;
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;
}
// Check if the file is completed
if (transferred != totalToTransfer) {
return Boolean.FALSE;
}
if (getMethod.getResponseBodyAsStream() != null) {
getMethod.getResponseBodyAsStream().close();
}
}
} catch (IOException e) {
Log_OC.e(TAG, "Error reading file", e);
} 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,6 +24,7 @@ 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
/**
@@ -124,11 +125,14 @@ 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,6 +25,7 @@ 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
@@ -56,6 +57,7 @@ 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
@@ -63,6 +65,7 @@ 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
@@ -764,7 +767,18 @@ open class ExtendedListFragment :
}
}
protected fun isAccountManagerInitialized(): Boolean = ::accountManager.isInitialized
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
}
}
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().getOnBackPressedDispatcher().onBackPressed();
requireActivity().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(file.getRemotePath(), user.getAccountName()))) {
|| (FileUploadHelper.Companion.instance().isUploading(user, file))) {
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(getFile().getRemotePath(), user.getAccountName())) {
if (FileUploadHelper.Companion.instance().isUploading(user, getFile())) {
binding.progressText.setText(R.string.uploader_upload_in_progress_ticker);
}
}
@@ -234,6 +234,12 @@ 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,6 +112,7 @@ public class LocalFileListFragment extends ExtendedListFragment implements
super.onActivityCreated(savedInstanceState);
mAdapter = new LocalFileListAdapter(mContainerActivity.isFolderPickerMode(),
mContainerActivity.getInitialDirectory(),
this,
preferences,
getActivity(),
@@ -255,30 +256,32 @@ public class LocalFileListFragment extends ExtendedListFragment implements
* @param directory Directory to be listed
*/
public void listDirectory(File directory) {
if (directory == null) {
directory = (mDirectory != null) ? mDirectory : Environment.getExternalStorageDirectory();
if (directory == null) return;
}
// 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;
// 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
}
}
}
// if that's not a directory -> List its parent
if (!directory.isDirectory()) {
Log_OC.w(TAG, "You see, that is not a directory -> " + directory);
directory = directory.getParentFile();
}
// 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,8 +77,6 @@ class OCFileListBottomSheetDialog(
colorImageView(menuIconScanDocUpload, ColorRole.PRIMARY)
colorImageView(menuIconMkdir, ColorRole.PRIMARY)
colorImageView(menuIconAddFolderInfo, ColorRole.PRIMARY)
colorViewBackground(binding.bottomSheet, ColorRole.SURFACE)
}
}
}
@@ -277,6 +277,12 @@ 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();
@@ -1241,11 +1247,6 @@ 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());
@@ -2324,15 +2325,4 @@ 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,9 +445,7 @@ class UnifiedSearchFragment :
private fun searchInCurrentDirectory(query: String) {
currentDir?.run {
val files = storageManager
.searchFilesByName(this, accountManager.user.accountName, query)
.filter { !it.isEncrypted }
val files = storageManager.searchFilesByName(this, accountManager.user.accountName, query)
adapter.setDataCurrentDirItems(files)
}
}
@@ -464,6 +462,6 @@ class UnifiedSearchFragment :
override fun openFile(remotePath: String, showMoreActions: Boolean) {
this.showMoreActions = showMoreActions
vm.getRemoteFile(remotePath)
vm.openFile(remotePath)
}
}
@@ -404,7 +404,7 @@ public class BackupListFragment extends FileFragment implements Injectable {
private void closeFragment() {
ContactsPreferenceActivity contactsPreferenceActivity = (ContactsPreferenceActivity) getActivity();
if (contactsPreferenceActivity != null) {
contactsPreferenceActivity.getOnBackPressedDispatcher().onBackPressed();
contactsPreferenceActivity.onBackPressed();
}
}
@@ -34,7 +34,6 @@ 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;
@@ -43,7 +42,6 @@ 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;
@@ -88,6 +86,7 @@ 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;
@@ -98,7 +97,6 @@ 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.
@@ -1008,22 +1006,17 @@ public class FileOperationsHelper {
}
}
final var fileDownloadHelper = FileDownloadHelper.Companion.instance();
if (fileDownloadHelper.isDownloading(currentUser, file)) {
if (FileDownloadHelper.Companion.instance().isDownloading(currentUser, file)) {
List<OCFile> files = fileActivity.getStorageManager().getAllFilesRecursivelyInsideFolder(file);
fileDownloadHelper.cancelPendingOrCurrentDownloads(currentUser, files);
FileDownloadHelper.Companion.instance().cancelPendingOrCurrentDownloads(currentUser, files);
}
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;
});
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!");
}
}
}
@@ -23,7 +23,6 @@ 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 {
onBackPressedDispatcher.onBackPressed()
onBackPressed()
return true
}
}
@@ -14,7 +14,6 @@ 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
@@ -56,7 +55,6 @@ 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.
@@ -125,7 +123,6 @@ class PreviewImageActivity :
observeWorkerState()
applyDisplayCutOutTopPadding()
handleBackPress()
}
private fun applyDisplayCutOutTopPadding() {
@@ -217,25 +214,9 @@ class PreviewImageActivity :
}
}
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 onBackPressed() {
sendRefreshSearchEventBroadcast()
super.onBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
@@ -297,6 +278,9 @@ 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()
@@ -304,9 +288,12 @@ class PreviewImageActivity :
}
}
if (result.isSuccess) {
updateViewPagerAfterDeletionAndAdvanceForward()
if (user.isPresent) {
initViewPager(user.get())
}
viewPager?.setCurrentItem(nextPosition, true)
previewImagePagerAdapter?.delete(deletePosition)
} else if (operation is SynchronizeFileOperation) {
onSynchronizeFileOperationFinish(result)
}
@@ -63,9 +63,7 @@ class PreviewImagePagerAdapter : FragmentStateAdapter {
imageFiles = mStorageManager.getFolderImages(parentFolder, onlyOnDevice)
val sortOrder = preferences.getSortOrderByFolder(parentFolder)
val foldersBeforeFiles = preferences.isSortFoldersBeforeFiles()
val favoritesFirst = preferences.isSortFavoritesFirst()
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList(), foldersBeforeFiles, favoritesFirst)
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList()).toMutableList()
mObsoleteFragments = HashSet()
mObsoletePositions = HashSet()
@@ -103,9 +101,7 @@ class PreviewImagePagerAdapter : FragmentStateAdapter {
if (type == VirtualFolderType.FAVORITE) {
val sortOrder = preferences.getSortOrderByType(FileSortOrder.Type.favoritesListView)
val foldersBeforeFiles = preferences.isSortFoldersBeforeFiles()
val favoritesFirst = preferences.isSortFavoritesFirst()
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList(), foldersBeforeFiles, favoritesFirst)
imageFiles = sortOrder.sortCloudFiles(imageFiles.toMutableList()).toMutableList()
}
mObsoleteFragments = HashSet()
@@ -205,11 +201,4 @@ 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().onBackPressedDispatcher.onBackPressed() }
requireActivity().runOnUiThread { requireActivity().onBackPressed() }
}
companion object {
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff. Show more