Merge pull request #435 from owncloud/ssl_dialogs_refactored_in_just_one
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SynchronizeFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2013 ownCloud Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2,
6 * as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 */
17
18 package com.owncloud.android.operations;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Vector;
31
32 import org.apache.http.HttpStatus;
33 import android.accounts.Account;
34 import android.content.Context;
35 import android.content.Intent;
36 //import android.support.v4.content.LocalBroadcastManager;
37
38 import com.owncloud.android.datamodel.FileDataStorageManager;
39 import com.owncloud.android.datamodel.OCFile;
40
41 import com.owncloud.android.lib.common.OwnCloudClient;
42 import com.owncloud.android.lib.resources.shares.OCShare;
43 import com.owncloud.android.lib.common.operations.RemoteOperation;
44 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
45 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
46 import com.owncloud.android.lib.resources.shares.GetRemoteSharesForFileOperation;
47 import com.owncloud.android.lib.resources.files.FileUtils;
48 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
49 import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
50 import com.owncloud.android.lib.resources.files.RemoteFile;
51
52 import com.owncloud.android.syncadapter.FileSyncAdapter;
53 import com.owncloud.android.utils.FileStorageUtils;
54 import com.owncloud.android.utils.Log_OC;
55
56
57
58 /**
59 * Remote operation performing the synchronization of the list of files contained
60 * in a folder identified with its remote path.
61 *
62 * Fetches the list and properties of the files contained in the given folder, including their
63 * properties, and updates the local database with them.
64 *
65 * Does NOT enter in the child folders to synchronize their contents also.
66 *
67 * @author David A. Velasco
68 */
69 public class SynchronizeFolderOperation extends RemoteOperation {
70
71 private static final String TAG = SynchronizeFolderOperation.class.getSimpleName();
72
73 public static final String EVENT_SINGLE_FOLDER_CONTENTS_SYNCED = SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_CONTENTS_SYNCED";
74 public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED = SynchronizeFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
75
76 /** Time stamp for the synchronization process in progress */
77 private long mCurrentSyncTime;
78
79 /** Remote folder to synchronize */
80 private OCFile mLocalFolder;
81
82 /** Access to the local database */
83 private FileDataStorageManager mStorageManager;
84
85 /** Account where the file to synchronize belongs */
86 private Account mAccount;
87
88 /** Android context; necessary to send requests to the download service */
89 private Context mContext;
90
91 /** Files and folders contained in the synchronized folder after a successful operation */
92 private List<OCFile> mChildren;
93
94 /** Counter of conflicts found between local and remote files */
95 private int mConflictsFound;
96
97 /** Counter of failed operations in synchronization of kept-in-sync files */
98 private int mFailsInFavouritesFound;
99
100 /** Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and couldn't be copied automatically into it */
101 private Map<String, String> mForgottenLocalFiles;
102
103 /** 'True' means that this operation is part of a full account synchronization */
104 private boolean mSyncFullAccount;
105
106 /** 'True' means that Share resources bound to the files into the folder should be refreshed also */
107 private boolean mIsShareSupported;
108
109 /** 'True' means that the remote folder changed from last synchronization and should be fetched */
110 private boolean mRemoteFolderChanged;
111
112
113 /**
114 * Creates a new instance of {@link SynchronizeFolderOperation}.
115 *
116 * @param remoteFolderPath Remote folder to synchronize.
117 * @param currentSyncTime Time stamp for the synchronization process in progress.
118 * @param localFolderId Identifier in the local database of the folder to synchronize.
119 * @param updateFolderProperties 'True' means that the properties of the folder should be updated also, not just its content.
120 * @param syncFullAccount 'True' means that this operation is part of a full account synchronization.
121 * @param dataStorageManager Interface with the local database.
122 * @param account ownCloud account where the folder is located.
123 * @param context Application context.
124 */
125 public SynchronizeFolderOperation( OCFile folder,
126 long currentSyncTime,
127 boolean syncFullAccount,
128 boolean isShareSupported,
129 FileDataStorageManager dataStorageManager,
130 Account account,
131 Context context ) {
132 mLocalFolder = folder;
133 mCurrentSyncTime = currentSyncTime;
134 mSyncFullAccount = syncFullAccount;
135 mIsShareSupported = isShareSupported;
136 mStorageManager = dataStorageManager;
137 mAccount = account;
138 mContext = context;
139 mForgottenLocalFiles = new HashMap<String, String>();
140 mRemoteFolderChanged = false;
141 }
142
143
144 public int getConflictsFound() {
145 return mConflictsFound;
146 }
147
148 public int getFailsInFavouritesFound() {
149 return mFailsInFavouritesFound;
150 }
151
152 public Map<String, String> getForgottenLocalFiles() {
153 return mForgottenLocalFiles;
154 }
155
156 /**
157 * Returns the list of files and folders contained in the synchronized folder, if called after synchronization is complete.
158 *
159 * @return List of files and folders contained in the synchronized folder.
160 */
161 public List<OCFile> getChildren() {
162 return mChildren;
163 }
164
165 /**
166 * Performs the synchronization.
167 *
168 * {@inheritDoc}
169 */
170 @Override
171 protected RemoteOperationResult run(OwnCloudClient client) {
172 RemoteOperationResult result = null;
173 mFailsInFavouritesFound = 0;
174 mConflictsFound = 0;
175 mForgottenLocalFiles.clear();
176
177 if (FileUtils.PATH_SEPARATOR.equals(mLocalFolder.getRemotePath()) && !mSyncFullAccount) {
178 updateOCVersion(client);
179 }
180
181 result = checkForChanges(client);
182
183 if (result.isSuccess()) {
184 if (mRemoteFolderChanged) {
185 result = fetchAndSyncRemoteFolder(client);
186 } else {
187 mChildren = mStorageManager.getFolderContent(mLocalFolder);
188 }
189 }
190
191 if (!mSyncFullAccount) {
192 sendLocalBroadcast(EVENT_SINGLE_FOLDER_CONTENTS_SYNCED, mLocalFolder.getRemotePath(), result);
193 }
194
195 if (result.isSuccess() && mIsShareSupported) {
196 RemoteOperationResult shareResult = refreshSharesForFolder(client);
197 if (shareResult.getCode() != ResultCode.FILE_NOT_FOUND) {
198 result = shareResult;
199 } // else , keep the previous result ; being conservative for servers where Sharing API is supported, but disabled
200 }
201
202 if (!mSyncFullAccount) {
203 sendLocalBroadcast(EVENT_SINGLE_FOLDER_SHARES_SYNCED, mLocalFolder.getRemotePath(), result);
204 }
205
206 return result;
207
208 }
209
210
211 private void updateOCVersion(OwnCloudClient client) {
212 UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
213 RemoteOperationResult result = update.execute(client);
214 if (result.isSuccess()) {
215 mIsShareSupported = update.getOCVersion().isSharedSupported();
216 }
217 }
218
219
220 private RemoteOperationResult checkForChanges(OwnCloudClient client) {
221 mRemoteFolderChanged = false;
222 RemoteOperationResult result = null;
223 String remotePath = null;
224
225 remotePath = mLocalFolder.getRemotePath();
226 Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
227
228 // remote request
229 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
230 result = operation.execute(client);
231 if (result.isSuccess()){
232 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
233
234 // check if remote and local folder are different
235 mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
236
237 result = new RemoteOperationResult(ResultCode.OK);
238
239 Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " + (mRemoteFolderChanged ? "changed" : "not changed"));
240
241 } else {
242 // check failed
243 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
244 removeLocalFolder();
245 }
246 if (result.isException()) {
247 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage(), result.getException());
248 } else {
249 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " + result.getLogMessage());
250 }
251 }
252
253 return result;
254 }
255
256
257 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
258 String remotePath = mLocalFolder.getRemotePath();
259 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
260 RemoteOperationResult result = operation.execute(client);
261 Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
262
263 if (result.isSuccess()) {
264 synchronizeData(result.getData(), client);
265 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
266 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT); // should be different result, but will do the job
267 }
268 } else {
269 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
270 removeLocalFolder();
271 }
272
273 return result;
274 }
275
276
277 private void removeLocalFolder() {
278 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
279 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
280 mStorageManager.removeFolder(mLocalFolder, true, (mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)));
281 }
282 }
283
284
285 /**
286 * Synchronizes the data retrieved from the server about the contents of the target folder
287 * with the current data in the local database.
288 *
289 * Grants that mChildren is updated with fresh data after execution.
290 *
291 * @param folderAndFiles Remote folder and children files in Folder
292 *
293 * @param client Client instance to the remote server where the data were
294 * retrieved.
295 * @return 'True' when any change was made in the local data, 'false' otherwise.
296 */
297 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
298 // get 'fresh data' from the database
299 mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
300
301 // parse data from remote folder
302 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
303 remoteFolder.setParentId(mLocalFolder.getParentId());
304 remoteFolder.setFileId(mLocalFolder.getFileId());
305
306 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath() + " changed - starting update of local data ");
307
308 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
309 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
310
311 // get current data about local contents of the folder to synchronize
312 List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
313 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
314 for (OCFile file : localFiles) {
315 localFilesMap.put(file.getRemotePath(), file);
316 }
317
318 // loop to update every child
319 OCFile remoteFile = null, localFile = null;
320 for (int i=1; i<folderAndFiles.size(); i++) {
321 /// new OCFile instance with the data from the server
322 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
323 remoteFile.setParentId(mLocalFolder.getFileId());
324
325 /// retrieve local data for the read file
326 //localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
327 localFile = localFilesMap.remove(remoteFile.getRemotePath());
328
329 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in the server side)
330 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
331 if (localFile != null) {
332 // some properties of local state are kept unmodified
333 remoteFile.setFileId(localFile.getFileId());
334 remoteFile.setKeepInSync(localFile.keepInSync());
335 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
336 remoteFile.setModificationTimestampAtLastSyncForData(localFile.getModificationTimestampAtLastSyncForData());
337 remoteFile.setStoragePath(localFile.getStoragePath());
338 remoteFile.setEtag(localFile.getEtag()); // eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
339 if (remoteFile.isFolder()) {
340 remoteFile.setFileLength(localFile.getFileLength()); // TODO move operations about size of folders to FileContentProvider
341 }
342 } else {
343 remoteFile.setEtag(""); // remote eTag will not be updated unless contents are synchronized (Synchronize[File|Folder]Operation with remoteFile as parameter)
344 }
345
346 /// check and fix, if needed, local storage path
347 checkAndFixForeignStoragePath(remoteFile); // fixing old policy - now local files must be copied into the ownCloud local folder
348 searchForLocalFileInDefaultPath(remoteFile); // legacy
349
350 /// prepare content synchronization for kept-in-sync files
351 if (remoteFile.keepInSync()) {
352 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
353 remoteFile,
354 mStorageManager,
355 mAccount,
356 true,
357 mContext
358 );
359 filesToSyncContents.add(operation);
360 }
361
362 updatedFiles.add(remoteFile);
363 }
364
365 // save updated contents in local database; all at once, trying to get a best performance in database update (not a big deal, indeed)
366 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
367
368 // request for the synchronization of file contents AFTER saving current remote properties
369 startContentSynchronizations(filesToSyncContents, client);
370
371 mChildren = updatedFiles;
372 }
373
374 /**
375 * Performs a list of synchronization operations, determining if a download or upload is needed or
376 * if exists conflict due to changes both in local and remote contents of the each file.
377 *
378 * If download or upload is needed, request the operation to the corresponding service and goes on.
379 *
380 * @param filesToSyncContents Synchronization operations to execute.
381 * @param client Interface to the remote ownCloud server.
382 */
383 private void startContentSynchronizations(List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client) {
384 RemoteOperationResult contentsResult = null;
385 for (SynchronizeFileOperation op: filesToSyncContents) {
386 contentsResult = op.execute(client); // returns without waiting for upload or download finishes
387 if (!contentsResult.isSuccess()) {
388 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
389 mConflictsFound++;
390 } else {
391 mFailsInFavouritesFound++;
392 if (contentsResult.getException() != null) {
393 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage(), contentsResult.getException());
394 } else {
395 Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
396 }
397 }
398 } // won't let these fails break the synchronization process
399 }
400 }
401
402
403 public boolean isMultiStatus(int status) {
404 return (status == HttpStatus.SC_MULTI_STATUS);
405 }
406
407 /**
408 * Creates and populates a new {@link OCFile} object with the data read from the server.
409 *
410 * @param remote remote file read from the server (remote file or folder).
411 * @return New OCFile instance representing the remote resource described by we.
412 */
413 private OCFile fillOCFile(RemoteFile remote) {
414 OCFile file = new OCFile(remote.getRemotePath());
415 file.setCreationTimestamp(remote.getCreationTimestamp());
416 file.setFileLength(remote.getLength());
417 file.setMimetype(remote.getMimeType());
418 file.setModificationTimestamp(remote.getModifiedTimestamp());
419 file.setEtag(remote.getEtag());
420 return file;
421 }
422
423
424 /**
425 * Checks the storage path of the OCFile received as parameter. If it's out of the local ownCloud folder,
426 * tries to copy the file inside it.
427 *
428 * If the copy fails, the link to the local file is nullified. The account of forgotten files is kept in
429 * {@link #mForgottenLocalFiles}
430 *)
431 * @param file File to check and fix.
432 */
433 private void checkAndFixForeignStoragePath(OCFile file) {
434 String storagePath = file.getStoragePath();
435 String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, file);
436 if (storagePath != null && !storagePath.equals(expectedPath)) {
437 /// fix storagePaths out of the local ownCloud folder
438 File originalFile = new File(storagePath);
439 if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
440 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
441 file.setStoragePath(null);
442
443 } else {
444 InputStream in = null;
445 OutputStream out = null;
446 try {
447 File expectedFile = new File(expectedPath);
448 File expectedParent = expectedFile.getParentFile();
449 expectedParent.mkdirs();
450 if (!expectedParent.isDirectory()) {
451 throw new IOException("Unexpected error: parent directory could not be created");
452 }
453 expectedFile.createNewFile();
454 if (!expectedFile.isFile()) {
455 throw new IOException("Unexpected error: target file could not be created");
456 }
457 in = new FileInputStream(originalFile);
458 out = new FileOutputStream(expectedFile);
459 byte[] buf = new byte[1024];
460 int len;
461 while ((len = in.read(buf)) > 0){
462 out.write(buf, 0, len);
463 }
464 file.setStoragePath(expectedPath);
465
466 } catch (Exception e) {
467 Log_OC.e(TAG, "Exception while copying foreign file " + expectedPath, e);
468 mForgottenLocalFiles.put(file.getRemotePath(), storagePath);
469 file.setStoragePath(null);
470
471 } finally {
472 try {
473 if (in != null) in.close();
474 } catch (Exception e) {
475 Log_OC.d(TAG, "Weird exception while closing input stream for " + storagePath + " (ignoring)", e);
476 }
477 try {
478 if (out != null) out.close();
479 } catch (Exception e) {
480 Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath + " (ignoring)", e);
481 }
482 }
483 }
484 }
485 }
486
487
488 private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
489 RemoteOperationResult result = null;
490
491 // remote request
492 GetRemoteSharesForFileOperation operation = new GetRemoteSharesForFileOperation(mLocalFolder.getRemotePath(), false, true);
493 result = operation.execute(client);
494
495 if (result.isSuccess()) {
496 // update local database
497 ArrayList<OCShare> shares = new ArrayList<OCShare>();
498 for(Object obj: result.getData()) {
499 shares.add((OCShare) obj);
500 }
501 mStorageManager.saveSharesInFolder(shares, mLocalFolder);
502 }
503
504 return result;
505 }
506
507
508 /**
509 * Scans the default location for saving local copies of files searching for
510 * a 'lost' file with the same full name as the {@link OCFile} received as
511 * parameter.
512 *
513 * @param file File to associate a possible 'lost' local file.
514 */
515 private void searchForLocalFileInDefaultPath(OCFile file) {
516 if (file.getStoragePath() == null && !file.isFolder()) {
517 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
518 if (f.exists()) {
519 file.setStoragePath(f.getAbsolutePath());
520 file.setLastSyncDateForData(f.lastModified());
521 }
522 }
523 }
524
525
526 /**
527 * Sends a message to any application component interested in the progress of the synchronization.
528 *
529 * @param event
530 * @param dirRemotePath Remote path of a folder that was just synchronized (with or without success)
531 * @param result
532 */
533 private void sendLocalBroadcast(String event, String dirRemotePath, RemoteOperationResult result) {
534 Log_OC.d(TAG, "Send broadcast " + event);
535 Intent intent = new Intent(event);
536 intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, mAccount.name);
537 if (dirRemotePath != null) {
538 intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
539 }
540 intent.putExtra(FileSyncAdapter.EXTRA_RESULT, result);
541 mContext.sendStickyBroadcast(intent);
542 //LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
543 }
544
545
546 public boolean getRemoteFolderChanged() {
547 return mRemoteFolderChanged;
548 }
549
550 }