1 /* ownCloud Android client application
2 * Copyright (C) 2012-2014 ownCloud Inc.
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.
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.
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/>.
18 package com
.owncloud
.android
.operations
;
20 import android
.accounts
.Account
;
21 import android
.content
.Context
;
22 import android
.content
.Intent
;
23 import android
.util
.Log
;
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
;
39 import org
.apache
.http
.HttpStatus
;
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
;
51 import java
.util
.Vector
;
53 //import android.support.v4.content.LocalBroadcastManager;
57 * Remote operation performing the synchronization of the list of files contained
58 * in a folder identified with its remote path.
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.
63 * Does NOT enter in the child folders to synchronize their contents also.
65 * @author David A. Velasco
67 public class SyncFolderOperation
extends SyncOperation
{
69 private static final String TAG
= SyncFolderOperation
.class.getSimpleName();
71 /** Time stamp for the synchronization process in progress */
72 private long mCurrentSyncTime
;
74 /** Remote folder to synchronize */
75 private OCFile mLocalFolder
;
77 /** Access to the local database */
78 private FileDataStorageManager mStorageManager
;
80 /** Account where the file to synchronize belongs */
81 private Account mAccount
;
83 /** Android context; necessary to send requests to the download service */
84 private Context mContext
;
86 /** Files and folders contained in the synchronized folder after a successful operation */
87 private List
<OCFile
> mChildren
;
89 /** Counter of conflicts found between local and remote files */
90 private int mConflictsFound
;
92 /** Counter of failed operations in synchronization of kept-in-sync files */
93 private int mFailsInFavouritesFound
;
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
99 private Map
<String
, String
> mForgottenLocalFiles
;
101 /** 'True' means that the remote folder changed and should be fetched */
102 private boolean mRemoteFolderChanged
;
106 * Creates a new instance of {@link SyncFolderOperation}.
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.
113 public SyncFolderOperation(Context context
, String remotePath
, Account account
, long currentSyncTime
){
114 mLocalFolder
= new OCFile(remotePath
);
115 mCurrentSyncTime
= currentSyncTime
;
116 mStorageManager
= getStorageManager();
119 mForgottenLocalFiles
= new HashMap
<String
, String
>();
120 mRemoteFolderChanged
= false
;
124 public int getConflictsFound() {
125 return mConflictsFound
;
128 public int getFailsInFavouritesFound() {
129 return mFailsInFavouritesFound
;
132 public Map
<String
, String
> getForgottenLocalFiles() {
133 return mForgottenLocalFiles
;
137 * Returns the list of files and folders contained in the synchronized folder,
138 * if called after synchronization is complete.
140 * @return List of files and folders contained in the synchronized folder.
142 public List
<OCFile
> getChildren() {
147 * Performs the synchronization.
152 protected RemoteOperationResult
run(OwnCloudClient client
) {
153 RemoteOperationResult result
= null
;
154 mFailsInFavouritesFound
= 0;
156 mForgottenLocalFiles
.clear();
158 result
= checkForChanges(client
);
160 if (result
.isSuccess()) {
161 if (mRemoteFolderChanged
) {
162 result
= fetchAndSyncRemoteFolder(client
);
164 mChildren
= mStorageManager
.getFolderContent(mLocalFolder
);
172 private RemoteOperationResult
checkForChanges(OwnCloudClient client
) {
173 mRemoteFolderChanged
= true
;
174 RemoteOperationResult result
= null
;
175 String remotePath
= null
;
177 remotePath
= mLocalFolder
.getRemotePath();
178 Log_OC
.d(TAG
, "Checking changes in " + mAccount
.name
+ remotePath
);
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));
186 // check if remote and local folder are different
187 mRemoteFolderChanged
=
188 !(remoteFolder
.getEtag().equalsIgnoreCase(mLocalFolder
.getEtag()));
190 result
= new RemoteOperationResult(ResultCode
.OK
);
192 Log_OC
.i(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
193 (mRemoteFolderChanged ?
"changed" : "not changed"));
197 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
) {
200 if (result
.isException()) {
201 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
202 result
.getLogMessage(), result
.getException());
204 Log_OC
.e(TAG
, "Checked " + mAccount
.name
+ remotePath
+ " : " +
205 result
.getLogMessage());
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
);
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
226 if (result
.getCode() == ResultCode
.FILE_NOT_FOUND
)
234 private void removeLocalFolder() {
235 if (mStorageManager
.fileExists(mLocalFolder
.getFileId())) {
236 String currentSavePath
= FileStorageUtils
.getSavePath(mAccount
.name
);
237 mStorageManager
.removeFolder(
240 ( mLocalFolder
.isDown() &&
241 mLocalFolder
.getStoragePath().startsWith(currentSavePath
)
249 * Synchronizes the data retrieved from the server about the contents of the target folder
250 * with the current data in the local database.
252 * Grants that mChildren is updated with fresh data after execution.
254 * @param folderAndFiles Remote folder and children files in Folder
256 * @param client Client instance to the remote server where the data were
258 * @return 'True' when any change was made in the local data, 'false' otherwise
260 private void synchronizeData(ArrayList
<Object
> folderAndFiles
, OwnCloudClient client
) {
261 // get 'fresh data' from the database
262 mLocalFolder
= mStorageManager
.getFileByPath(mLocalFolder
.getRemotePath());
264 // parse data from remote folder
265 OCFile remoteFolder
= fillOCFile((RemoteFile
)folderAndFiles
.get(0));
266 remoteFolder
.setParentId(mLocalFolder
.getParentId());
267 remoteFolder
.setFileId(mLocalFolder
.getFileId());
269 Log_OC
.d(TAG
, "Remote folder " + mLocalFolder
.getRemotePath()
270 + " changed - starting update of local data ");
272 List
<OCFile
> updatedFiles
= new Vector
<OCFile
>(folderAndFiles
.size() - 1);
273 List
<SynchronizeFileOperation
> filesToSyncContents
= new Vector
<SynchronizeFileOperation
>();
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
);
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());
289 /// retrieve local data for the read file
290 // localFile = mStorageManager.getFileByPath(remoteFile.getRemotePath());
291 localFile
= localFilesMap
.remove(remoteFile
.getRemotePath());
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()
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");
315 remoteFile
.setPublicLink(localFile
.getPublicLink());
316 remoteFile
.setShareByLink(localFile
.isShareByLink());
318 // remote eTag will not be updated unless contents are synchronized
319 // (Synchronize[File|Folder]Operation with remoteFile as parameter)
320 remoteFile
.setEtag("");
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
328 /// prepare content synchronization for kept-in-sync files
329 if (remoteFile
.keepInSync()) {
330 SynchronizeFileOperation operation
= new SynchronizeFileOperation( localFile
,
337 filesToSyncContents
.add(operation
);
340 if (!remoteFile
.isFolder()) {
341 // Start file download
342 requestForDownloadFile(remoteFile
);
344 // Run new SyncFolderOperation for download children files recursively from a folder
345 RemoteOperation synchFolderOp
= new SyncFolderOperation( mContext
,
346 remoteFile
.getRemotePath(),
350 synchFolderOp
.execute(mAccount
, mContext
, null
, null
);
353 updatedFiles
.add(remoteFile
);
356 // save updated contents in local database
357 mStorageManager
.saveFolder(remoteFolder
, updatedFiles
, localFilesMap
.values());
359 // request for the synchronization of file contents AFTER saving current remote properties
360 startContentSynchronizations(filesToSyncContents
, client
);
362 mChildren
= updatedFiles
;
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.
369 * If download or upload is needed, request the operation to the corresponding service and goes
372 * @param filesToSyncContents Synchronization operations to execute.
373 * @param client Interface to the remote ownCloud server.
375 private void startContentSynchronizations(
376 List
<SynchronizeFileOperation
> filesToSyncContents
, OwnCloudClient client
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
) {
385 mFailsInFavouritesFound
++;
386 if (contentsResult
.getException() != null
) {
387 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
388 + contentsResult
.getLogMessage(), contentsResult
.getException());
390 Log_OC
.e(TAG
, "Error while synchronizing favourites : "
391 + contentsResult
.getLogMessage());
394 } // won't let these fails break the synchronization process
399 public boolean isMultiStatus(int status
) {
400 return (status
== HttpStatus
.SC_MULTI_STATUS
);
404 * Creates and populates a new {@link com.owncloud.android.datamodel.OCFile} object with the data read from the server.
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.
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());
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.
426 * If the copy fails, the link to the local file is nullified. The account of forgotten
427 * files is kept in {@link #mForgottenLocalFiles}
429 * @param file File to check and fix.
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
);
442 InputStream
in = null
;
443 OutputStream out
= null
;
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"
453 expectedFile
.createNewFile();
454 if (!expectedFile
.isFile()) {
455 throw new IOException("Unexpected error: target file could not be created");
457 in = new FileInputStream(originalFile
);
458 out
= new FileOutputStream(expectedFile
);
459 byte[] buf
= new byte[1024];
461 while ((len
= in.read(buf
)) > 0){
462 out
.write(buf
, 0, len
);
464 file
.setStoragePath(expectedPath
);
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
);
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
);
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
);
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
495 * @param file File to associate a possible 'lost' local file.
497 private void searchForLocalFileInDefaultPath(OCFile file
) {
498 if (file
.getStoragePath() == null
&& !file
.isFolder()) {
499 File f
= new File(FileStorageUtils
.getDefaultSavePathFor(mAccount
.name
, file
));
501 file
.setStoragePath(f
.getAbsolutePath());
502 file
.setLastSyncDateForData(f
.lastModified());
508 * Requests for a download to the FileDownloader service
510 * @param file OCFile object representing the file to download
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
);
519 public boolean getRemoteFolderChanged() {
520 return mRemoteFolderChanged
;