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