Fixed local path NULL when making favourite a file not down ; fixed change of local...
[pub/Android/ownCloud.git] / src / com / owncloud / android / syncadapter / FileSyncAdapter.java
index 1f0d908..ea833d4 100644 (file)
 package com.owncloud.android.syncadapter;\r
 \r
 import java.io.IOException;\r
+import java.net.UnknownHostException;\r
 import java.util.List;\r
 \r
 import org.apache.jackrabbit.webdav.DavException;\r
-import org.json.JSONObject;\r
 \r
-import com.owncloud.android.AccountUtils;\r
 import com.owncloud.android.R;\r
-import com.owncloud.android.authenticator.AccountAuthenticator;\r
 import com.owncloud.android.datamodel.DataStorageManager;\r
 import com.owncloud.android.datamodel.FileDataStorageManager;\r
 import com.owncloud.android.datamodel.OCFile;\r
+//<<<<<<< HEAD
 import com.owncloud.android.operations.RemoteOperationResult;\r
 import com.owncloud.android.operations.SynchronizeFolderOperation;\r
+import com.owncloud.android.operations.UpdateOCVersionOperation;\r
+/*=======
+import com.owncloud.android.files.services.FileDownloader;\r
+import com.owncloud.android.files.services.FileObserverService;\r
 import com.owncloud.android.utils.OwnCloudVersion;\r
+>>>>>>> origin/master*/
 \r
 import android.accounts.Account;\r
 import android.app.Notification;\r
@@ -45,7 +49,6 @@ import android.content.Intent;
 import android.content.SyncResult;\r
 import android.os.Bundle;\r
 import android.util.Log;\r
-import eu.alefzero.webdav.WebdavClient;\r
 \r
 /**\r
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
@@ -67,11 +70,15 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private boolean mIsManualSync;\r
     private int mFailedResultsCounter;    \r
     private RemoteOperationResult mLastFailedResult;\r
+    private SyncResult mSyncResult;\r
     \r
     public FileSyncAdapter(Context context, boolean autoInitialize) {\r
         super(context, autoInitialize);\r
     }\r
 \r
+    /**\r
+     * {@inheritDoc}\r
+     */\r
     @Override\r
     public synchronized void onPerformSync(Account account, Bundle extras,\r
             String authority, ContentProviderClient provider,\r
@@ -81,32 +88,43 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
         mFailedResultsCounter = 0;\r
         mLastFailedResult = null;\r
-        \r
+        mSyncResult = syncResult;\r
+        mSyncResult.fullSyncRequested = false;\r
+        mSyncResult.delayUntil = 60*60*24; // sync after 24h\r
+\r
         this.setAccount(account);\r
         this.setContentProvider(provider);\r
         this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));\r
+        try {\r
+            this.initClientForCurrentAccount();\r
+        } catch (UnknownHostException e) {\r
+            /// the account is unknown for the Synchronization Manager, or unreachable for this context; don't try this again\r
+            mSyncResult.tooManyRetries = true;\r
+            notifyFailedSynchronization();\r
+            return;\r
+        }\r
         \r
-        Log.d(TAG, "syncing owncloud account " + account.name);\r
-\r
+        Log.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");\r
         sendStickyBroadcast(true, null, null);  // message to signal the start of the synchronization to the UI\r
         \r
         try {\r
             updateOCVersion();\r
             mCurrentSyncTime = System.currentTimeMillis();\r
             if (!mCancellation) {\r
-                fetchData(OCFile.PATH_SEPARATOR, syncResult, DataStorageManager.ROOT_PARENT_ID);\r
+                fetchData(OCFile.PATH_SEPARATOR, DataStorageManager.ROOT_PARENT_ID);\r
                 \r
             } else {\r
                 Log.d(TAG, "Leaving synchronization before any remote request due to cancellation was requested");\r
             }\r
             \r
+            \r
         } finally {\r
             // it's important making this although very unexpected errors occur; that's the reason for the finally\r
             \r
             if (mFailedResultsCounter > 0 && mIsManualSync) {\r
                 /// don't let the system synchronization manager retries MANUAL synchronizations\r
                 //      (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)\r
-                syncResult.tooManyRetries = true;\r
+                mSyncResult.tooManyRetries = true;\r
                 \r
                 /// notify the user about the failure of MANUAL synchronization\r
                 notifyFailedSynchronization();\r
@@ -136,31 +154,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Updates the locally stored version value of the ownCloud server\r
      */\r
     private void updateOCVersion() {\r
-        String statUrl = getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_BASE_URL);\r
-        statUrl += AccountUtils.STATUS_PATH;\r
-        \r
-        try {\r
-            String result = getClient().getResultAsString(statUrl);\r
-            if (result != null) {\r
-                try {\r
-                    JSONObject json = new JSONObject(result);\r
-                    if (json != null && json.getString("version") != null) {\r
-                        OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version"));\r
-                        if (ocver.isVersionValid()) {\r
-                            getAccountManager().setUserData(getAccount(), AccountAuthenticator.KEY_OC_VERSION, ocver.toString());\r
-                            Log.d(TAG, "Got new OC version " + ocver.toString());\r
-                        } else {\r
-                            Log.w(TAG, "Invalid version number received from server: " + json.getString("version"));\r
-                        }\r
-                    }\r
-                } catch (Throwable e) {\r
-                    Log.w(TAG, "Couldn't parse version response", e);\r
-                }\r
-            } else {\r
-                Log.w(TAG, "Problem while getting ocversion from server");\r
-            }\r
-        } catch (Exception e) {\r
-            Log.e(TAG, "Problem getting response from server", e);\r
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
+        RemoteOperationResult result = update.execute(getClient());\r
+        if (!result.isSuccess()) {\r
+            mLastFailedResult = result; \r
         }\r
     }\r
 \r
@@ -171,23 +168,12 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * \r
      * @param remotePath        Remote path to the folder to synchronize.\r
      * @param parentId          Database Id of the folder to synchronize.\r
-     * @param syncResult        Object to update for communicate results to the system's synchronization manager.        \r
      */\r
-    private void fetchData(String remotePath, SyncResult syncResult, long parentId) {\r
+    private void fetchData(String remotePath, long parentId) {\r
         \r
-        if (mFailedResultsCounter > MAX_FAILED_RESULTS && isFinisher(mLastFailedResult))\r
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
             return;\r
         \r
-        // get client object to connect to the remote ownCloud server\r
-        WebdavClient client = null;\r
-        try {\r
-            client = getClient();\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            Log.d(TAG, "Could not get client object while trying to synchronize - impossible to continue");\r
-            return;\r
-        }\r
-        \r
         // perform folder synchronization\r
         SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
                                                                                     mCurrentSyncTime, \r
@@ -196,7 +182,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
                                                                                     getAccount(), \r
                                                                                     getContext()\r
                                                                                   );\r
-        RemoteOperationResult result = synchFolderOp.execute(client);\r
+        RemoteOperationResult result = synchFolderOp.execute(getClient());\r
         \r
         \r
         // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
@@ -205,17 +191,44 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
         if (result.isSuccess()) {\r
             // synchronize children folders \r
             List<OCFile> children = synchFolderOp.getChildren();\r
-            fetchChildren(children, syncResult);    // beware of the 'hidden' recursion here!\r
+            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
             \r
+//<<<<<<< HEAD
         } else {\r
             if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
-                syncResult.stats.numAuthExceptions++;\r
+                mSyncResult.stats.numAuthExceptions++;\r
                 \r
             } else if (result.getException() instanceof DavException) {\r
-                syncResult.stats.numParseExceptions++;\r
+                mSyncResult.stats.numParseExceptions++;\r
                 \r
             } else if (result.getException() instanceof IOException) { \r
-                syncResult.stats.numIoExceptions++;\r
+                mSyncResult.stats.numIoExceptions++;\r
+/*=======
+                // insertion or update of files\r
+                List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);\r
+                for (int i = 1; i < resp.getResponses().length; ++i) {\r
+                    WebdavEntry we = new WebdavEntry(resp.getResponses()[i], getUri().getPath());\r
+                    OCFile file = fillOCFile(we);\r
+                    file.setParentId(parentId);\r
+                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null &&\r
+                            getStorageManager().getFileByPath(file.getRemotePath()).keepInSync() &&\r
+                            file.getModificationTimestamp() > getStorageManager().getFileByPath(file.getRemotePath())\r
+                                                                         .getModificationTimestamp()) {\r
+                        // first disable observer so we won't get file upload right after download\r
+                        Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());\r
+                        Intent intent = new Intent(getContext(), FileObserverService.class);\r
+                        intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);\r
+                        intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());\r
+                        getContext().startService(intent);\r
+                        intent = new Intent(this.getContext(), FileDownloader.class);\r
+                        intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());\r
+                        intent.putExtra(FileDownloader.EXTRA_FILE, file);\r
+                        file.setKeepInSync(true);\r
+                        getContext().startService(intent);\r
+                    }\r
+                    if (getStorageManager().getFileByPath(file.getRemotePath()) != null)\r
+                        file.setKeepInSync(getStorageManager().getFileByPath(file.getRemotePath()).keepInSync());\r
+>>>>>>> origin/master*/
                 \r
             }\r
             mFailedResultsCounter++;\r
@@ -246,14 +259,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
      * Synchronize data of folders in the list of received files\r
      * \r
      * @param files         Files to recursively fetch \r
-     * @param syncResult    Updated object to provide results to the Synchronization Manager\r
      */\r
-    private void fetchChildren(List<OCFile> files, SyncResult syncResult) {\r
+    private void fetchChildren(List<OCFile> files) {\r
         int i;\r
         for (i=0; i < files.size() && !mCancellation; i++) {\r
             OCFile newFile = files.get(i);\r
             if (newFile.isDirectory()) {\r
-                fetchData(newFile.getRemotePath(), syncResult, newFile.getFileId());\r
+                fetchData(newFile.getRemotePath(), newFile.getFileId());\r
             }\r
         }\r
         if (mCancellation && i <files.size()) Log.d(TAG, "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() + " because cancelation request");\r