Skip to content

Commit 73d794c

Browse files
committed
fix(auto-upload): calls
Signed-off-by: alperozturk96 <alper_ozturk@proton.me>
1 parent 6b8296a commit 73d794c

File tree

10 files changed

+91
-179
lines changed

10 files changed

+91
-179
lines changed

app/src/main/java/com/nextcloud/client/jobs/BackgroundJobFactory.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ import com.nextcloud.client.integrations.deck.DeckApi
2525
import com.nextcloud.client.jobs.autoUpload.AutoUploadWorker
2626
import com.nextcloud.client.jobs.autoUpload.FileSystemRepository
2727
import com.nextcloud.client.jobs.download.FileDownloadWorker
28+
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
2829
import com.nextcloud.client.jobs.metadata.MetadataWorker
2930
import com.nextcloud.client.jobs.offlineOperations.OfflineOperationsWorker
30-
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorker
3131
import com.nextcloud.client.jobs.upload.FileUploadWorker
3232
import com.nextcloud.client.logger.Logger
3333
import com.nextcloud.client.network.ConnectivityService

app/src/main/java/com/nextcloud/client/jobs/BackgroundJobManager.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,7 @@ interface BackgroundJobManager {
120120

121121
fun startImmediateFilesExportJob(files: Collection<OCFile>): LiveData<JobInfo?>
122122

123-
fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder)
124-
125-
fun startAutoUploadImmediately(
123+
fun startAutoUpload(
126124
syncedFolder: SyncedFolder,
127125
overridePowerSaving: Boolean = false,
128126
contentUris: Array<String?> = arrayOf()

app/src/main/java/com/nextcloud/client/jobs/BackgroundJobManagerImpl.kt

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -278,11 +278,11 @@ internal class BackgroundJobManagerImpl(
278278
.setTriggerContentMaxDelay(MAX_CONTENT_TRIGGER_DELAY_MS, TimeUnit.MILLISECONDS)
279279
.build()
280280

281-
val request = oneTimeRequestBuilder(ContentObserverWork::class, JOB_CONTENT_OBSERVER)
281+
val request = periodicRequestBuilder(ContentObserverWork::class, JOB_CONTENT_OBSERVER)
282282
.setConstraints(constrains)
283283
.build()
284284

285-
workManager.enqueueUniqueWork(JOB_CONTENT_OBSERVER, ExistingWorkPolicy.REPLACE, request)
285+
workManager.enqueueUniquePeriodicWork(JOB_CONTENT_OBSERVER, ExistingPeriodicWorkPolicy.KEEP, request)
286286
}
287287

288288
override fun schedulePeriodicContactsBackup(user: User) {
@@ -477,40 +477,7 @@ internal class BackgroundJobManagerImpl(
477477
)
478478
}
479479

480-
override fun schedulePeriodicFilesSyncJob(syncedFolder: SyncedFolder) {
481-
val syncedFolderID = syncedFolder.id
482-
483-
val arguments = Data.Builder()
484-
.putLong(AutoUploadWorker.SYNCED_FOLDER_ID, syncedFolderID)
485-
.build()
486-
487-
val constraints = Constraints.Builder()
488-
.setRequiredNetworkType(NetworkType.CONNECTED)
489-
.setRequiresCharging(syncedFolder.isChargingOnly)
490-
.build()
491-
492-
val request = periodicRequestBuilder(
493-
jobClass = AutoUploadWorker::class,
494-
jobName = JOB_PERIODIC_FILES_SYNC + "_" + syncedFolderID,
495-
intervalMins = DEFAULT_PERIODIC_JOB_INTERVAL_MINUTES,
496-
constraints = constraints
497-
)
498-
.setBackoffCriteria(
499-
BackoffPolicy.LINEAR,
500-
DEFAULT_BACKOFF_CRITERIA_DELAY_SEC,
501-
TimeUnit.SECONDS
502-
)
503-
.setInputData(arguments)
504-
.build()
505-
506-
workManager.enqueueUniquePeriodicWork(
507-
JOB_PERIODIC_FILES_SYNC + "_" + syncedFolderID,
508-
ExistingPeriodicWorkPolicy.KEEP,
509-
request
510-
)
511-
}
512-
513-
override fun startAutoUploadImmediately(
480+
override fun startAutoUpload(
514481
syncedFolder: SyncedFolder,
515482
overridePowerSaving: Boolean,
516483
contentUris: Array<String?>
@@ -533,6 +500,7 @@ internal class BackgroundJobManagerImpl(
533500
jobName = JOB_IMMEDIATE_FILES_SYNC + "_" + syncedFolderID
534501
)
535502
.setInputData(arguments)
503+
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
536504
.setConstraints(constraints)
537505
.setBackoffCriteria(
538506
BackoffPolicy.LINEAR,

app/src/main/java/com/nextcloud/client/jobs/ContentObserverWork.kt

Lines changed: 6 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -7,32 +7,25 @@
77
*/
88
package com.nextcloud.client.jobs
99

10-
import android.app.Notification
1110
import android.content.Context
12-
import androidx.core.app.NotificationCompat
1311
import androidx.work.CoroutineWorker
1412
import androidx.work.WorkerParameters
1513
import com.nextcloud.client.device.PowerManagementService
16-
import com.nextcloud.utils.ForegroundServiceHelper
17-
import com.owncloud.android.R
18-
import com.owncloud.android.datamodel.ForegroundServiceType
1914
import com.owncloud.android.datamodel.SyncedFolderProvider
2015
import com.owncloud.android.lib.common.utils.Log_OC
21-
import com.owncloud.android.ui.notifications.NotificationUtils
2216
import com.owncloud.android.utils.FilesSyncHelper
2317
import kotlinx.coroutines.Dispatchers
2418
import kotlinx.coroutines.withContext
2519

2620
/**
2721
* This work is triggered when OS detects change in media folders.
2822
*
29-
* It fires media detection job and sync job and finishes immediately.
23+
* It fires media detection worker and auto upload worker and finishes immediately.
3024
*
31-
* This job must not be started on API < 24.
3225
*/
3326
@Suppress("TooGenericExceptionCaught")
3427
class ContentObserverWork(
35-
private val context: Context,
28+
context: Context,
3629
private val params: WorkerParameters,
3730
private val syncedFolderProvider: SyncedFolderProvider,
3831
private val powerManagementService: PowerManagementService,
@@ -41,8 +34,6 @@ class ContentObserverWork(
4134

4235
companion object {
4336
private const val TAG = "🔍" + "ContentObserverWork"
44-
private const val CHANNEL_ID = NotificationUtils.NOTIFICATION_CHANNEL_CONTENT_OBSERVER
45-
private const val NOTIFICATION_ID = 774
4637
}
4738

4839
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
@@ -53,10 +44,6 @@ class ContentObserverWork(
5344
try {
5445
if (params.triggeredContentUris.isNotEmpty()) {
5546
Log_OC.d(TAG, "📸 content observer detected file changes.")
56-
57-
val notificationTitle = context.getString(R.string.content_observer_work_notification_title)
58-
val notification = createNotification(notificationTitle)
59-
updateForegroundInfo(notification)
6047
checkAndTriggerAutoUpload()
6148

6249
// prevent worker fail because of another worker
@@ -69,8 +56,6 @@ class ContentObserverWork(
6956
Log_OC.d(TAG, "⚠️ triggeredContentUris is empty — nothing to sync.")
7057
}
7158

72-
rescheduleSelf()
73-
7459
val result = Result.success()
7560
backgroundJobManager.logEndOfWorker(workerName, result)
7661
Log_OC.d(TAG, "finished")
@@ -81,34 +66,6 @@ class ContentObserverWork(
8166
}
8267
}
8368

84-
private suspend fun updateForegroundInfo(notification: Notification) {
85-
val foregroundInfo = ForegroundServiceHelper.createWorkerForegroundInfo(
86-
NOTIFICATION_ID,
87-
notification,
88-
ForegroundServiceType.DataSync
89-
)
90-
setForeground(foregroundInfo)
91-
}
92-
93-
private fun createNotification(title: String): Notification = NotificationCompat.Builder(context, CHANNEL_ID)
94-
.setContentTitle(title)
95-
.setSmallIcon(R.drawable.ic_find_in_page)
96-
.setOngoing(true)
97-
.setSound(null)
98-
.setVibrate(null)
99-
.setOnlyAlertOnce(true)
100-
.setPriority(NotificationCompat.PRIORITY_LOW)
101-
.setSilent(true)
102-
.build()
103-
104-
/**
105-
* Re-schedules this observer to ensure continuous monitoring of media changes.
106-
*/
107-
private fun rescheduleSelf() {
108-
Log_OC.d(TAG, "🔁 Rescheduling ContentObserverWork for continued observation.")
109-
backgroundJobManager.scheduleContentObserverJob()
110-
}
111-
11269
private suspend fun checkAndTriggerAutoUpload() = withContext(Dispatchers.IO) {
11370
if (powerManagementService.isPowerSavingEnabled) {
11471
Log_OC.w(TAG, "⚡ Power saving mode active — skipping file sync.")
@@ -124,15 +81,15 @@ class ContentObserverWork(
12481
val contentUris = params.triggeredContentUris.map { uri ->
12582
// adds uri strings e.g. content://media/external/images/media/2281
12683
uri.toString()
127-
}.toTypedArray()
84+
}.toTypedArray<String?>()
12885
Log_OC.d(TAG, "📄 Content uris detected")
12986

13087
try {
131-
FilesSyncHelper.startAutoUploadImmediatelyWithContentUris(
88+
FilesSyncHelper.startAutoUploadForEnabledSyncedFolders(
13289
syncedFolderProvider,
13390
backgroundJobManager,
134-
false,
135-
contentUris
91+
contentUris,
92+
false
13693
)
13794
Log_OC.d(TAG, "✅ auto upload triggered successfully for ${contentUris.size} file(s).")
13895
} catch (e: Exception) {

app/src/main/java/com/nextcloud/client/jobs/autoUpload/AutoUploadWorker.kt

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,11 +186,6 @@ class AutoUploadWorker(
186186
val currentTime = System.currentTimeMillis()
187187
val passedScanInterval = totalScanInterval <= currentTime
188188

189-
Log_OC.d(TAG, "lastScanTimestampMs: " + syncedFolder.lastScanTimestampMs)
190-
Log_OC.d(TAG, "totalScanInterval: $totalScanInterval")
191-
Log_OC.d(TAG, "currentTime: $currentTime")
192-
Log_OC.d(TAG, "passedScanInterval: $passedScanInterval")
193-
194189
if (!passedScanInterval && contentUris.isNullOrEmpty() && !overridePowerSaving) {
195190
Log_OC.w(
196191
TAG,
@@ -199,6 +194,8 @@ class AutoUploadWorker(
199194
return true
200195
}
201196

197+
Log_OC.d(TAG, "starting ...")
198+
202199
return false
203200
}
204201

@@ -208,6 +205,8 @@ class AutoUploadWorker(
208205
*/
209206
@Suppress("MagicNumber", "TooGenericExceptionCaught")
210207
private suspend fun collectFileChangesFromContentObserverWork(contentUris: Array<String>?) = try {
208+
Log_OC.d(TAG, "collecting file changes")
209+
211210
withContext(Dispatchers.IO) {
212211
if (contentUris.isNullOrEmpty()) {
213212
helper.insertEntries(syncedFolder, repository)
@@ -289,7 +288,7 @@ class AutoUploadWorker(
289288
Log_OC.w(TAG, "no more files to upload at lastId: $lastId")
290289
break
291290
}
292-
Log_OC.d(TAG, "Processing batch: lastId=$lastId, count=${filePathsWithIds.size}")
291+
Log_OC.d(TAG, "started, processing batch: lastId=$lastId, count=${filePathsWithIds.size}")
293292

294293
filePathsWithIds.forEach { (path, id) ->
295294
val file = File(path)

app/src/main/java/com/nextcloud/client/jobs/notification/WorkerNotificationManager.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,15 @@ open class WorkerNotificationManager(
8989
notification,
9090
ForegroundServiceType.DataSync
9191
)
92+
93+
fun createNotification(title: String, iconId: Int): Notification = notificationBuilder
94+
.setContentTitle(title)
95+
.setSmallIcon(iconId)
96+
.setOngoing(true)
97+
.setSound(null)
98+
.setVibrate(null)
99+
.setOnlyAlertOnce(true)
100+
.setPriority(NotificationCompat.PRIORITY_LOW)
101+
.setSilent(true)
102+
.build()
92103
}

app/src/main/java/com/owncloud/android/MainApp.java

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,8 @@
125125

126126

127127
/**
128-
* Main Application of the project.
129-
* Contains methods to build the "static" strings. These strings were before constants in different classes.
128+
* Main Application of the project. Contains methods to build the "static" strings. These strings were before constants
129+
* in different classes.
130130
*/
131131
public class MainApp extends Application implements HasAndroidInjector, NetworkChangeListener {
132132
public static final OwnCloudVersion OUTDATED_SERVER_VERSION = NextcloudVersion.nextcloud_30;
@@ -142,7 +142,7 @@ public class MainApp extends Application implements HasAndroidInjector, NetworkC
142142
private static boolean mOnlyOnDevice;
143143
private static boolean mOnlyPersonalFiles;
144144

145-
145+
146146
@Inject
147147
protected AppPreferences preferences;
148148

@@ -338,6 +338,10 @@ public void onCreate() {
338338
} catch (Exception e) {
339339
Log_OC.d("Debug", "Failed to disable uri exposure");
340340
}
341+
342+
Log_OC.d(TAG, "scheduleContentObserverJob, called");
343+
backgroundJobManager.scheduleContentObserverJob();
344+
341345
initSyncOperations(this,
342346
preferences,
343347
uploadsStorageManager,
@@ -347,8 +351,7 @@ public void onCreate() {
347351
backgroundJobManager,
348352
clock,
349353
viewThemeUtils,
350-
walledCheckCache,
351-
syncedFolderProvider);
354+
walledCheckCache);
352355
initContactsBackup(accountManager, backgroundJobManager);
353356
notificationChannels();
354357

@@ -371,9 +374,9 @@ public void onCreate() {
371374
if (!MDMConfig.INSTANCE.sendFilesSupport(this)) {
372375
disableDocumentsStorageProvider();
373376
}
374-
375-
376-
}
377+
378+
379+
}
377380

378381
public void disableDocumentsStorageProvider() {
379382
String packageName = getPackageName();
@@ -386,6 +389,10 @@ public void disableDocumentsStorageProvider() {
386389
private final LifecycleEventObserver lifecycleEventObserver = ((lifecycleOwner, event) -> {
387390
if (event == Lifecycle.Event.ON_START) {
388391
Log_OC.d(TAG, "APP IN FOREGROUND");
392+
FilesSyncHelper.startAutoUploadForEnabledSyncedFolders(syncedFolderProvider,
393+
backgroundJobManager,
394+
new String[]{},
395+
true);
389396
} else if (event == Lifecycle.Event.ON_STOP) {
390397
passCodeManager.setCanAskPin(true);
391398
Log_OC.d(TAG, "APP IN BACKGROUND");
@@ -403,7 +410,7 @@ private void setProxyForNonBrandedPlusClients() {
403410
Log_OC.d(TAG, "Error caught at setProxyForNonBrandedPlusClients: " + e);
404411
}
405412
}
406-
413+
407414
public static boolean isClientBranded() {
408415
return getAppContext().getResources().getBoolean(R.bool.is_branded_client);
409416
}
@@ -415,7 +422,8 @@ public static boolean isClientBrandedPlus() {
415422
private final IntentFilter restrictionsFilter = new IntentFilter(Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED);
416423

417424
private final BroadcastReceiver restrictionsReceiver = new BroadcastReceiver() {
418-
@Override public void onReceive(Context context, Intent intent) {
425+
@Override
426+
public void onReceive(Context context, Intent intent) {
419427
setProxyConfig();
420428
}
421429
};
@@ -605,8 +613,7 @@ public static void initSyncOperations(
605613
final BackgroundJobManager backgroundJobManager,
606614
final Clock clock,
607615
final ViewThemeUtils viewThemeUtils,
608-
final WalledCheckCache walledCheckCache,
609-
final SyncedFolderProvider syncedFolderProvider) {
616+
final WalledCheckCache walledCheckCache) {
610617
updateToAutoUpload(context);
611618
cleanOldEntries(clock);
612619
updateAutoUploadEntries(clock);
@@ -620,11 +627,9 @@ public static void initSyncOperations(
620627
}
621628

622629
if (!preferences.isAutoUploadInitialized()) {
623-
FilesSyncHelper.startAutoUploadImmediately(syncedFolderProvider, backgroundJobManager, false);
624630
preferences.setAutoUploadInit(true);
625631
}
626632

627-
FilesSyncHelper.scheduleFilesSyncForAllFoldersIfNeeded(appContext.get(), syncedFolderProvider, backgroundJobManager);
628633
FilesSyncHelper.restartUploadsIfNeeded(
629634
uploadsStorageManager,
630635
accountManager,
@@ -845,7 +850,6 @@ private static void updateToAutoUpload(Context context) {
845850
}
846851
}
847852

848-
849853

850854
private static void showAutoUploadAlertDialog(Context context) {
851855
new MaterialAlertDialogBuilder(context, R.style.Theme_ownCloud_Dialog)

0 commit comments

Comments
 (0)