-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathSynchronizeFolderOperation.java
More file actions
630 lines (523 loc) · 25.4 KB
/
Copy pathSynchronizeFolderOperation.java
File metadata and controls
630 lines (523 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2020 Chris Narkiewicz <hello@ezaquarii.com>
* SPDX-FileCopyrightText: 2018-2023 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2018 Andy Scherzinger <info@andy-scherzinger.de>
* SPDX-FileCopyrightText: 2016 ownCloud Inc.
* SPDX-FileCopyrightText: 2012-2013 David A. Velasco <dvelasco@solidgear.es>
* SPDX-License-Identifier: GPL-2.0-only AND (AGPL-3.0-or-later OR GPL-2.0-only)
*/
package com.owncloud.android.operations;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import com.nextcloud.client.account.User;
import com.nextcloud.client.jobs.download.FileDownloadHelper;
import com.nextcloud.client.jobs.folderDownload.FolderDownloadWorkerNotificationManager;
import com.nextcloud.common.NextcloudClient;
import com.nextcloud.utils.extensions.ExtensionsKt;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.e2e.v1.decrypted.DecryptedFolderMetadataFileV1;
import com.owncloud.android.datamodel.e2e.v2.decrypted.DecryptedFolderMetadataFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.operations.OperationCancelledException;
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.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.operations.common.SyncOperation;
import com.owncloud.android.services.OperationsService;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeTypeUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import kotlin.Unit;
/**
* Remote operation performing the synchronization of the list of files contained
* in a folder identified with its remote path.
* Fetches the list and properties of the files contained in the given folder, including their
* properties, and updates the local database with them.
* Does NOT enter in the child folders to synchronize their contents also, BUT requests for a new operation instance
* doing so.
*/
public class SynchronizeFolderOperation extends SyncOperation {
private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
/** Remote path of the folder to synchronize */
private String mRemotePath;
/** Account where the file to synchronize belongs */
private User user;
/** Android context; necessary to send requests to the download service */
private Context mContext;
/** Locally cached information about folder to synchronize */
private OCFile mLocalFolder;
/** Counter of conflicts found between local and remote files */
private int mConflictsFound;
/** Counter of failed operations in synchronization of kept-in-sync files */
private int mFailsInFileSyncsFound;
/**
* 'True' means that the remote folder changed and should be fetched
*/
private boolean mRemoteFolderChanged;
private List<OCFile> mFilesForDirectDownload;
// to avoid extra PROPFINDs when there was no change in the folder
private List<SynchronizeFileOperation> mFilesToSyncContents;
// this will be used for every file when 'folder synchronization' replaces 'folder download'
private final AtomicBoolean mCancellationRequested;
private final boolean useWorkerWithNotification;
private final boolean syncAll;
final FolderDownloadWorkerNotificationManager notificationManager;
/**
* Creates a new instance of {@link SynchronizeFolderOperation}.
*
* @param context Application context.
* @param remotePath Path to synchronize.
* @param user Nextcloud account where the folder is located.
*/
public SynchronizeFolderOperation(Context context,
String remotePath,
User user,
FileDataStorageManager storageManager,
boolean useWorkerWithNotification,
boolean syncAll) {
super(storageManager);
mRemotePath = remotePath;
this.user = user;
mContext = context;
mRemoteFolderChanged = false;
mFilesForDirectDownload = new Vector<>();
mFilesToSyncContents = new Vector<>();
mCancellationRequested = new AtomicBoolean(false);
this.useWorkerWithNotification = useWorkerWithNotification;
this.syncAll = syncAll;
notificationManager = new FolderDownloadWorkerNotificationManager(context, false,null);
}
/**
* Performs the synchronization.
*
* {@inheritDoc}
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
mFailsInFileSyncsFound = 0;
mConflictsFound = 0;
try {
// get locally cached information about folder
mLocalFolder = getStorageManager().getFileByPath(mRemotePath);
if (mLocalFolder == null) {
Log_OC.e(TAG, "Local folder is null, cannot run synchronize folder operation, remote path: " + mRemotePath);
return new RemoteOperationResult<>(ResultCode.FILE_NOT_FOUND);
}
result = checkForChanges(client);
if (result.isSuccess()) {
if (mRemoteFolderChanged || syncAll) {
result = fetchAndSyncRemoteFolder();
} else {
prepareOpsFromLocalKnowledge();
}
if (result.isSuccess()) {
syncContents();
}
}
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
} catch (OperationCancelledException e) {
result = new RemoteOperationResult(e);
}
return result;
}
private RemoteOperationResult checkForChanges(OwnCloudClient client) throws OperationCancelledException {
Log_OC.d(TAG, "Checking changes in " + user.getAccountName() + mRemotePath);
mRemoteFolderChanged = true;
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
// remote request
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
var result = operation.execute(client);
if (result.isSuccess() && result.getData().get(0) instanceof RemoteFile remoteFile) {
OCFile remoteFolder = FileStorageUtils.fillOCFile(remoteFile);
// check if remote and local folder are different
mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
result = new RemoteOperationResult<>(ResultCode.OK);
Log_OC.i(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
(mRemoteFolderChanged ? "changed" : "not changed"));
} else {
// check failed
if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
removeLocalFolder();
}
if (result.isException()) {
Log_OC.e(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
result.getLogMessage(), result.getException());
} else {
Log_OC.e(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
result.getLogMessage());
}
}
return result;
}
private RemoteOperationResult fetchAndSyncRemoteFolder() throws OperationCancelledException {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
NextcloudClient nextcloudClient;
try {
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, mContext);
} catch (AccountUtils.AccountNotFoundException | NullPointerException e) {
Log_OC.e(TAG, "Could not create NextcloudClient to synchronize " + mRemotePath, e);
return new RemoteOperationResult<>(e);
}
ReadFolderRemoteOperation operation = new ReadFolderRemoteOperation(mRemotePath);
var result = operation.execute(nextcloudClient);
Log_OC.d(TAG, "Synchronizing " + user.getAccountName() + mRemotePath);
Log_OC.d(TAG, "Synchronizing remote id" + mLocalFolder.getRemoteId());
if (result.isSuccess()) {
synchronizeData(result.getData());
if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
// should be a different result code, but will do the job
}
} else {
if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
removeLocalFolder();
}
}
return result;
}
private void removeLocalFolder() {
FileDataStorageManager storageManager = getStorageManager();
if (storageManager.fileExists(mLocalFolder.getFileId())) {
String currentSavePath = FileStorageUtils.getSavePath(user.getAccountName());
storageManager.removeFolder(
mLocalFolder,
true,
mLocalFolder.isDown() // TODO: debug, I think this is always false for folders
&& mLocalFolder.getStoragePath().startsWith(currentSavePath)
);
}
}
/**
* Synchronizes the data retrieved from the server about the contents of the target folder
* with the current data in the local database.
*
* @param folderAndFiles Remote folder and children files in Folder
*/
private void synchronizeData(List<Object> folderAndFiles) throws OperationCancelledException {
// parse data from remote folder
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
remoteFolder.setParentId(mLocalFolder.getParentId());
remoteFolder.setFileId(mLocalFolder.getFileId());
Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
mFilesForDirectDownload.clear();
mFilesToSyncContents.clear();
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
FileDataStorageManager storageManager = getStorageManager();
// if local folder is encrypted, download fresh metadata
boolean encryptedAncestor = FileStorageUtils.checkEncryptionStatus(remoteFolder, storageManager);
mLocalFolder.setEncrypted(encryptedAncestor);
// update permission
mLocalFolder.setPermissions(remoteFolder.getPermissions());
// update richWorkspace
mLocalFolder.setRichWorkspace(remoteFolder.getRichWorkspace());
Object object = RefreshFolderOperation.getDecryptedFolderMetadata(encryptedAncestor,
mLocalFolder,
getClient(),
user,
mContext);
if (mLocalFolder.isEncrypted() && object == null) {
throw new IllegalStateException("metadata is null!");
}
// get current data about local contents of the folder to synchronize
Map<String, OCFile> localFilesMap = RefreshFolderOperation.prefillLocalFilesMap(object,storageManager.getFolderContent(mLocalFolder, false));
// loop to synchronize every child
List<OCFile> updatedFiles = new ArrayList<>(folderAndFiles.size() - 1);
OCFile remoteFile;
OCFile localFile;
OCFile updatedFile;
RemoteFile remote;
for (int i = 1; i < folderAndFiles.size(); i++) {
/// new OCFile instance with the data from the server
remote = (RemoteFile) folderAndFiles.get(i);
remoteFile = FileStorageUtils.fillOCFile(remote);
/// new OCFile instance to merge fresh data from server with local state
updatedFile = FileStorageUtils.fillOCFile(remote);
updatedFile.setParentId(mLocalFolder.getFileId());
/// retrieve local data for the read file
localFile = localFilesMap.remove(remoteFile.getRemotePath());
// TODO better implementation is needed
if (localFile == null) {
localFile = storageManager.getFileByPath(updatedFile.getRemotePath());
}
/// add to updatedFile data about LOCAL STATE (not existing in server)
updateLocalStateData(remoteFile, localFile, updatedFile);
/// check and fix, if needed, local storage path
FileStorageUtils.searchForLocalFileInDefaultPath(updatedFile, user.getAccountName());
// update file name for encrypted files
if (object instanceof DecryptedFolderMetadataFileV1 metadataFile) {
RefreshFolderOperation.updateFileNameForEncryptedFileV1(storageManager, metadataFile, updatedFile);
} else if (object instanceof DecryptedFolderMetadataFile metadataFile) {
RefreshFolderOperation.updateFileNameForEncryptedFile(storageManager, metadataFile, updatedFile);
}
// we parse content, so either the folder itself or its direct parent (which we check) must be encrypted
boolean encrypted = updatedFile.isEncrypted() || mLocalFolder.isEncrypted();
updatedFile.setEncrypted(encrypted);
syncFileOrFolder(remoteFile, localFile);
updatedFiles.add(updatedFile);
}
// update file name for encrypted files
if (object instanceof DecryptedFolderMetadataFileV1 metadataFile) {
RefreshFolderOperation.updateFileNameForEncryptedFileV1(storageManager, metadataFile, mLocalFolder);
} else if (object instanceof DecryptedFolderMetadataFile metadataFile) {
RefreshFolderOperation.updateFileNameForEncryptedFile(storageManager, metadataFile, mLocalFolder);
}
// save updated contents in local database
storageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
mLocalFolder.setLastSyncDateForData(System.currentTimeMillis());
storageManager.saveFile(mLocalFolder);
}
private void updateLocalStateData(OCFile remoteFile, OCFile localFile, OCFile updatedFile) {
updatedFile.setLastSyncDateForProperties(System.currentTimeMillis());
if (localFile != null) {
updatedFile.setFileId(localFile.getFileId());
updatedFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
updatedFile.setModificationTimestampAtLastSyncForData(
localFile.getModificationTimestampAtLastSyncForData()
);
updatedFile.setStoragePath(localFile.getStoragePath());
// eTag will not be updated unless file CONTENTS are synchronized
updatedFile.setEtag(localFile.getEtag());
if (updatedFile.isFolder()) {
updatedFile.setFileLength(localFile.getFileLength());
// TODO move operations about size of folders to FileContentProvider
} else if (mRemoteFolderChanged && MimeTypeUtil.isImage(remoteFile) &&
remoteFile.getModificationTimestamp() !=
localFile.getModificationTimestamp()) {
updatedFile.setUpdateThumbnailNeeded(true);
Log_OC.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
}
updatedFile.setSharedViaLink(localFile.isSharedViaLink());
updatedFile.setSharedWithSharee(localFile.isSharedWithSharee());
updatedFile.setEtagInConflict(localFile.getEtagInConflict());
} else {
// remote eTag will not be updated unless file CONTENTS are synchronized
updatedFile.setEtag("");
}
}
/**
* Schedules synchronization for the given remote file or folder.
* <p>
* If the remote file is a regular file, a {@link SynchronizeFileOperation} is created
* and added to the list of pending file synchronizations.
* If the remote file is a folder, the method triggers a folder synchronization operation,
* which recursively synchronizes all nested files and subfolders.
* </p>
*
* @param remoteFile the remote file or folder to synchronize
* @param localFile the corresponding local file or folder
* @throws OperationCancelledException if the synchronization was cancelled
*/
@SuppressFBWarnings("JLM")
private void syncFileOrFolder(OCFile remoteFile, OCFile localFile) throws OperationCancelledException {
if (remoteFile.isFolder()) {
synchronized (mCancellationRequested) {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
startSyncFolderOperation(remoteFile.getRemotePath());
}
} else {
SynchronizeFileOperation operation = new SynchronizeFileOperation(
localFile,
remoteFile,
user,
true,
mContext,
getStorageManager(),
useWorkerWithNotification
);
mFilesToSyncContents.add(operation);
}
}
private void prepareOpsFromLocalKnowledge() throws OperationCancelledException {
List<OCFile> children = getStorageManager().getFolderContent(mLocalFolder, false);
for (OCFile child : children) {
if (!child.isFolder()) {
if (!child.isDown()) {
mFilesForDirectDownload.add(child);
} else {
/// this should result in direct upload of files that were locally modified
SynchronizeFileOperation operation = new SynchronizeFileOperation(
child,
child.getEtagInConflict() != null ? child : null,
user,
true,
mContext,
getStorageManager(),
useWorkerWithNotification
);
mFilesToSyncContents.add(operation);
}
}
}
}
private void syncContents() throws OperationCancelledException {
startDirectDownloads();
startContentSynchronizations(mFilesToSyncContents);
updateETag();
}
/**
* Updates the eTag of the local folder after a successful synchronization.
* This ensures that any changes to local files, which may alter the eTag, are correctly reflected.
*/
private void updateETag() {
NextcloudClient nextcloudClient;
try {
nextcloudClient = OwnCloudClientFactory.createNextcloudClient(user, mContext);
} catch (AccountUtils.AccountNotFoundException | NullPointerException e) {
Log_OC.e(TAG, "Could not create NextcloudClient to update eTag of " + mRemotePath, e);
return;
}
ReadFolderRemoteOperation operation = new ReadFolderRemoteOperation(mRemotePath);
final var result = operation.execute(nextcloudClient);
if (!result.isSuccess()) {
Log_OC.w(TAG, "Cannot update eTag, read folder operation is failed");
return;
}
if (result.getData().get(0) instanceof RemoteFile remoteFile) {
String eTag = remoteFile.getEtag();
mLocalFolder.setEtag(eTag);
final FileDataStorageManager storageManager = getStorageManager();
storageManager.saveFile(mLocalFolder);
}
}
private void startDirectDownloads() {
final var fileDownloadHelper = FileDownloadHelper.Companion.instance();
if (useWorkerWithNotification) {
fileDownloadHelper.downloadFolder(mLocalFolder, user.getAccountName());
} else {
try {
for (OCFile file: mFilesForDirectDownload) {
synchronized (mCancellationRequested) {
if (mCancellationRequested.get()) {
break;
}
}
if (file == null) {
continue;
}
final var operation = new DownloadFileOperation(user, file, mContext);
var result = operation.execute(getClient());
String filename = file.getFileName();
if (filename == null) {
continue;
}
if (result.isSuccess()) {
fileDownloadHelper.saveFile(file, operation, getStorageManager());
Log_OC.d(TAG, "startDirectDownloads completed for: " + file.getFileName());
} else {
Log_OC.d(TAG, "startDirectDownloads failed for: " + file.getFileName());
}
}
} catch (Exception e) {
Log_OC.d(TAG, "Exception caught at startDirectDownloads" + e);
}
}
}
/**
* Performs a list of synchronization operations, determining if a download or upload is needed
* or if exists conflict due to changes both in local and remote contents of the each file.
* <p>
* If download or upload is needed, request the operation to the corresponding service and goes on.
*
* @param filesToSyncContents Synchronization operations to execute.
*/
private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents) throws OperationCancelledException {
Log_OC.v(TAG, "Starting content synchronization... ");
int total = filesToSyncContents.size();
String folderName = mLocalFolder.getFileName();
for (int current = 0; current < filesToSyncContents.size(); current++) {
if (mCancellationRequested.get()) {
throw new OperationCancelledException();
}
final var synchronizeFileOperation = filesToSyncContents.get(current);
final var result = synchronizeFileOperation.execute(mContext);
final var file = synchronizeFileOperation.getLocalFile();
if (result.isSuccess() && file != null) {
notificationManager.showProgressNotification(folderName, file.getFileName(), current, total);
} else {
if (result.getCode() == ResultCode.SYNC_CONFLICT) {
mConflictsFound++;
} else {
mFailsInFileSyncsFound++;
String message = "Error while synchronizing file : ";
if (result.getException() != null) {
message = message + result.getLogMessage() + " Exception: "
+ result.getException().getMessage();
} else {
message = message + result.getLogMessage();
}
Log_OC.e(TAG, message);
}
}
}
ExtensionsKt.mainThread(0L, () -> {
notificationManager.dismiss();
return Unit.INSTANCE;
});
}
/**
* Cancel operation
*/
public void cancel() {
mCancellationRequested.set(true);
}
public Optional<String> getFolderNameFromPath() {
if (mLocalFolder == null) {
return Optional.empty();
}
String path = mLocalFolder.getStoragePath();
if (!TextUtils.isEmpty(path)) {
File folder = new File(path);
return Optional.of(folder.getName());
}
String filepath = FileStorageUtils.getDefaultSavePathFor(user.getAccountName(), mLocalFolder);
File folder = new File(filepath);
return Optional.of(folder.getName());
}
private void startSyncFolderOperation(String path) {
Intent intent = new Intent(mContext, OperationsService.class);
intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
intent.putExtra(OperationsService.EXTRA_ACCOUNT, user.toPlatformAccount());
intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, path);
intent.putExtra(OperationsService.EXTRA_SYNC_ALL, syncAll);
mContext.startService(intent);
}
public String getRemotePath() {
return mRemotePath;
}
public String getAccountName() {
return user.getAccountName();
}
public Long getFolderId() {
if (mLocalFolder == null) {
return null;
}
return mLocalFolder.getFileId();
}
}