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