Resolve recursion on new SyncFolderOperation creating new instances of SynFolderOpera...
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / SyncFolderOperation.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 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 android.accounts.Account;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.util.Log;
24
25 import com.owncloud.android.datamodel.FileDataStorageManager;
26 import com.owncloud.android.datamodel.OCFile;
27 import com.owncloud.android.files.services.FileDownloader;
28 import com.owncloud.android.lib.common.OwnCloudClient;
29 import com.owncloud.android.lib.common.operations.RemoteOperation;
30 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
31 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
32 import com.owncloud.android.lib.common.utils.Log_OC;
33 import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
34 import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation;
35 import com.owncloud.android.lib.resources.files.RemoteFile;
36 import com.owncloud.android.operations.common.SyncOperation;
37 import com.owncloud.android.utils.FileStorageUtils;
38
39 import org.apache.http.HttpStatus;
40
41 import java.io.File;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.OutputStream;
47 import java.util.ArrayList;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Vector;
52
53 //import android.support.v4.content.LocalBroadcastManager;
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 SyncFolderOperation extends SyncOperation {
68
69 private static final String TAG = SyncFolderOperation.class.getSimpleName();
70
71 /** Time stamp for the synchronization process in progress */
72 private long mCurrentSyncTime;
73
74 /** Remote folder to synchronize */
75 private OCFile mLocalFolder;
76
77 /** Access to the local database */
78 private FileDataStorageManager mStorageManager;
79
80 /** Account where the file to synchronize belongs */
81 private Account mAccount;
82
83 /** Android context; necessary to send requests to the download service */
84 private Context mContext;
85
86 /** Files and folders contained in the synchronized folder after a successful operation */
87 private List<OCFile> mChildren;
88
89 /** Counter of conflicts found between local and remote files */
90 private int mConflictsFound;
91
92 /** Counter of failed operations in synchronization of kept-in-sync files */
93 private int mFailsInFavouritesFound;
94
95 /**
96 * Map of remote and local paths to files that where locally stored in a location
97 * out of the ownCloud folder and couldn't be copied automatically into it
98 **/
99 private Map<String, String> mForgottenLocalFiles;
100
101 /** 'True' means that the remote folder changed and should be fetched */
102 private boolean mRemoteFolderChanged;
103
104
105 /**
106 * Creates a new instance of {@link SyncFolderOperation}.
107 *
108 * @param context Application context.
109 * @param remotePath Path to synchronize.
110 * @param account ownCloud account where the folder is located.
111 * @param currentSyncTime Time stamp for the synchronization process in progress.
112 */
113 public SyncFolderOperation(Context context, String remotePath, Account account, long currentSyncTime){
114 mLocalFolder = new OCFile(remotePath);
115 mCurrentSyncTime = currentSyncTime;
116 mStorageManager = getStorageManager();
117 mAccount = account;
118 mContext = context;
119 mForgottenLocalFiles = new HashMap<String, String>();
120 mRemoteFolderChanged = false;
121 }
122
123
124 public int getConflictsFound() {
125 return mConflictsFound;
126 }
127
128 public int getFailsInFavouritesFound() {
129 return mFailsInFavouritesFound;
130 }
131
132 public Map<String, String> getForgottenLocalFiles() {
133 return mForgottenLocalFiles;
134 }
135
136 /**
137 * Returns the list of files and folders contained in the synchronized folder,
138 * if called after synchronization is complete.
139 *
140 * @return List of files and folders contained in the synchronized folder.
141 */
142 public List<OCFile> getChildren() {
143 return mChildren;
144 }
145
146 /**
147 * Performs the synchronization.
148 *
149 * {@inheritDoc}
150 */
151 @Override
152 protected RemoteOperationResult run(OwnCloudClient client) {
153 RemoteOperationResult result = null;
154 mFailsInFavouritesFound = 0;
155 mConflictsFound = 0;
156 mForgottenLocalFiles.clear();
157
158 result = checkForChanges(client);
159
160 if (result.isSuccess()) {
161 if (mRemoteFolderChanged) {
162 result = fetchAndSyncRemoteFolder(client);
163 } else {
164 mChildren = mStorageManager.getFolderContent(mLocalFolder);
165 }
166 }
167
168 return result;
169
170 }
171
172 private RemoteOperationResult checkForChanges(OwnCloudClient client) {
173 mRemoteFolderChanged = true;
174 RemoteOperationResult result = null;
175 String remotePath = null;
176
177 remotePath = mLocalFolder.getRemotePath();
178 Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
179
180 // remote request
181 ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
182 result = operation.execute(client);
183 if (result.isSuccess()){
184 OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
185
186 // check if remote and local folder are different
187 mRemoteFolderChanged =
188 !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
189
190 result = new RemoteOperationResult(ResultCode.OK);
191
192 Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
193 (mRemoteFolderChanged ? "changed" : "not changed"));
194
195 } else {
196 // check failed
197 if (result.getCode() == ResultCode.FILE_NOT_FOUND) {
198 removeLocalFolder();
199 }
200 if (result.isException()) {
201 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
202 result.getLogMessage(), result.getException());
203 } else {
204 Log_OC.e(TAG, "Checked " + mAccount.name + remotePath + " : " +
205 result.getLogMessage());
206 }
207 }
208
209 return result;
210 }
211
212
213 private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
214 String remotePath = mLocalFolder.getRemotePath();
215 ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath);
216 RemoteOperationResult result = operation.execute(client);
217 Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
218
219 if (result.isSuccess()) {
220 synchronizeData(result.getData(), client);
221 if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
222 result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
223 // should be a different result code, but will do the job
224 }
225 } else {
226 if (result.getCode() == ResultCode.FILE_NOT_FOUND)
227 removeLocalFolder();
228 }
229
230 return result;
231 }
232
233
234 private void removeLocalFolder() {
235 if (mStorageManager.fileExists(mLocalFolder.getFileId())) {
236 String currentSavePath = FileStorageUtils.getSavePath(mAccount.name);
237 mStorageManager.removeFolder(
238 mLocalFolder,
239 true,
240 ( mLocalFolder.isDown() &&
241 mLocalFolder.getStoragePath().startsWith(currentSavePath)
242 )
243 );
244 }
245 }
246
247
248 /**
249 * Synchronizes the data retrieved from the server about the contents of the target folder
250 * with the current data in the local database.
251 *
252 * Grants that mChildren is updated with fresh data after execution.
253 *
254 * @param folderAndFiles Remote folder and children files in Folder
255 *
256 * @param client Client instance to the remote server where the data were
257 * retrieved.
258 * @return 'True' when any change was made in the local data, 'false' otherwise
259 */
260 private void synchronizeData(ArrayList<Object> folderAndFiles, OwnCloudClient client) {
261 // get 'fresh data' from the database
262 mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
263
264 // parse data from remote folder
265 OCFile remoteFolder = fillOCFile((RemoteFile)folderAndFiles.get(0));
266 remoteFolder.setParentId(mLocalFolder.getParentId());
267 remoteFolder.setFileId(mLocalFolder.getFileId());
268
269 Log_OC.d(TAG, "Remote folder " + mLocalFolder.getRemotePath()
270 + " changed - starting update of local data ");
271
272 List<OCFile> updatedFiles = new Vector<OCFile>(folderAndFiles.size() - 1);
273 List<SynchronizeFileOperation> filesToSyncContents = new Vector<SynchronizeFileOperation>();
274
275 // get current data about local contents of the folder to synchronize
276 List<OCFile> localFiles = mStorageManager.getFolderContent(mLocalFolder);
277 Map<String, OCFile> localFilesMap = new HashMap<String, OCFile>(localFiles.size());
278 for (OCFile file : localFiles) {
279 localFilesMap.put(file.getRemotePath(), file);
280 }
281
282 // loop to update every child
283 OCFile remoteFile = null, localFile = null;
284 for (int i=1; i<folderAndFiles.size(); i++) {
285 /// new OCFile instance with the data from the server
286 remoteFile = fillOCFile((RemoteFile)folderAndFiles.get(i));
287 remoteFile.setParentId(mLocalFolder.getFileId());
288
289 /// retrieve local data for the read file
290 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
291 localFile = localFilesMap.remove(remoteFile.getRemotePath());
292
293 /// add to the remoteFile (the new one) data about LOCAL STATE (not existing in server)
294 remoteFile.setLastSyncDateForProperties(mCurrentSyncTime);
295 if (localFile != null) {
296 // some properties of local state are kept unmodified
297 remoteFile.setFileId(localFile.getFileId());
298 remoteFile.setKeepInSync(localFile.keepInSync());
299 remoteFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
300 remoteFile.setModificationTimestampAtLastSyncForData(
301 localFile.getModificationTimestampAtLastSyncForData()
302 );
303 remoteFile.setStoragePath(localFile.getStoragePath());
304 // eTag will not be updated unless contents are synchronized
305 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
306 remoteFile.setEtag(localFile.getEtag());
307 if (remoteFile.isFolder()) {
308 remoteFile.setFileLength(localFile.getFileLength());
309 // TODO move operations about size of folders to FileContentProvider
310 } else if (mRemoteFolderChanged && remoteFile.isImage() &&
311 remoteFile.getModificationTimestamp() != localFile.getModificationTimestamp()) {
312 remoteFile.setNeedsUpdateThumbnail(true);
313 Log.d(TAG, "Image " + remoteFile.getFileName() + " updated on the server");
314 }
315 remoteFile.setPublicLink(localFile.getPublicLink());
316 remoteFile.setShareByLink(localFile.isShareByLink());
317 } else {
318 // remote eTag will not be updated unless contents are synchronized
319 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
320 remoteFile.setEtag("");
321 }
322
323 /// check and fix, if needed, local storage path
324 checkAndFixForeignStoragePath(remoteFile); // policy - local files are COPIED
325 // into the ownCloud local folder;
326 searchForLocalFileInDefaultPath(remoteFile); // legacy
327
328 /// prepare content synchronization for kept-in-sync files
329 if (remoteFile.keepInSync()) {
330 SynchronizeFileOperation operation = new SynchronizeFileOperation( localFile,
331 remoteFile,
332 mAccount,
333 true,
334 mContext
335 );
336
337 filesToSyncContents.add(operation);
338 }
339
340 if (!remoteFile.isFolder()) {
341 // Start file download
342 requestForDownloadFile(remoteFile);
343 } else {
344 // Run new SyncFolderOperation for download children files recursively from a folder
345 RemoteOperation synchFolderOp = new SyncFolderOperation( mContext,
346 remoteFile.getRemotePath(),
347 mAccount,
348 mCurrentSyncTime);
349
350 synchFolderOp.execute(mAccount, mContext, null, null);
351 }
352
353 updatedFiles.add(remoteFile);
354 }
355
356 // save updated contents in local database
357 mStorageManager.saveFolder(remoteFolder, updatedFiles, localFilesMap.values());
358
359 // request for the synchronization of file contents AFTER saving current remote properties
360 startContentSynchronizations(filesToSyncContents, client);
361
362 mChildren = updatedFiles;
363 }
364
365 /**
366 * Performs a list of synchronization operations, determining if a download or upload is needed
367 * or if exists conflict due to changes both in local and remote contents of the each file.
368 *
369 * If download or upload is needed, request the operation to the corresponding service and goes
370 * on.
371 *
372 * @param filesToSyncContents Synchronization operations to execute.
373 * @param client Interface to the remote ownCloud server.
374 */
375 private void startContentSynchronizations(
376 List<SynchronizeFileOperation> filesToSyncContents, OwnCloudClient client
377 ) {
378 RemoteOperationResult contentsResult = null;
379 for (SynchronizeFileOperation op: filesToSyncContents) {
380 contentsResult = op.execute(mStorageManager, mContext); // async
381 if (!contentsResult.isSuccess()) {
382 if (contentsResult.getCode() == ResultCode.SYNC_CONFLICT) {
383 mConflictsFound++;
384 } else {
385 mFailsInFavouritesFound++;
386 if (contentsResult.getException() != null) {
387 Log_OC.e(TAG, "Error while synchronizing favourites : "
388 + contentsResult.getLogMessage(), contentsResult.getException());
389 } else {
390 Log_OC.e(TAG, "Error while synchronizing favourites : "
391 + contentsResult.getLogMessage());
392 }
393 }
394 } // won't let these fails break the synchronization process
395 }
396 }
397
398
399 public boolean isMultiStatus(int status) {
400 return (status == HttpStatus.SC_MULTI_STATUS);
401 }
402
403 /**
404 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
405 *
406 * @param remote remote file read from the server (remote file or folder).
407 * @return New OCFile instance representing the remote resource described by we.
408 */
409 private OCFile fillOCFile(RemoteFile remote) {
410 OCFile file = new OCFile(remote.getRemotePath());
411 file.setCreationTimestamp(remote.getCreationTimestamp());
412 file.setFileLength(remote.getLength());
413 file.setMimetype(remote.getMimeType());
414 file.setModificationTimestamp(remote.getModifiedTimestamp());
415 file.setEtag(remote.getEtag());
416 file.setPermissions(remote.getPermissions());
417 file.setRemoteId(remote.getRemoteId());
418 return file;
419 }
420
421
422 /**
423 * Checks the storage path of the OCFile received as parameter.
424 * If it's out of the local ownCloud folder, 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
427 * files is kept in {@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(
450 "Unexpected error: parent directory could not be created"
451 );
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 "
476 + storagePath + " (ignoring)", e);
477 }
478 try {
479 if (out != null) out.close();
480 } catch (Exception e) {
481 Log_OC.d(TAG, "Weird exception while closing output stream for "
482 + expectedPath + " (ignoring)", e);
483 }
484 }
485 }
486 }
487 }
488
489
490 /**
491 * Scans the default location for saving local copies of files searching for
492 * a 'lost' file with the same full name as the {@link com.owncloud.android.datamodel.OCFile} received as
493 * parameter.
494 *
495 * @param file File to associate a possible 'lost' local file.
496 */
497 private void searchForLocalFileInDefaultPath(OCFile file) {
498 if (file.getStoragePath() == null && !file.isFolder()) {
499 File f = new File(FileStorageUtils.getDefaultSavePathFor(mAccount.name, file));
500 if (f.exists()) {
501 file.setStoragePath(f.getAbsolutePath());
502 file.setLastSyncDateForData(f.lastModified());
503 }
504 }
505 }
506
507 /**
508 * Requests for a download to the FileDownloader service
509 *
510 * @param file OCFile object representing the file to download
511 */
512 private void requestForDownloadFile(OCFile file) {
513 Intent i = new Intent(mContext, FileDownloader.class);
514 i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
515 i.putExtra(FileDownloader.EXTRA_FILE, file);
516 mContext.startService(i);
517 }
518
519 public boolean getRemoteFolderChanged() {
520 return mRemoteFolderChanged;
521 }
522
523 }