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