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 7b803fc..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
-import java.util.Vector;\r
 \r
 import org.apache.jackrabbit.webdav.DavException;\r
-import org.apache.jackrabbit.webdav.MultiStatus;\r
-import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;\r
 \r
+import com.owncloud.android.R;\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.accounts.AuthenticatorException;\r
-import android.accounts.OperationCanceledException;\r
+import android.app.Notification;\r
+import android.app.NotificationManager;\r
+import android.app.PendingIntent;\r
 import android.content.ContentProviderClient;\r
+import android.content.ContentResolver;\r
 import android.content.Context;\r
 import android.content.Intent;\r
 import android.content.SyncResult;\r
 import android.os.Bundle;\r
 import android.util.Log;\r
-import eu.alefzero.webdav.WebdavEntry;\r
-import eu.alefzero.webdav.WebdavUtils;\r
 \r
 /**\r
  * SyncAdapter implementation for syncing sample SyncAdapter contacts to the\r
@@ -50,253 +58,256 @@ import eu.alefzero.webdav.WebdavUtils;
  */\r
 public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {\r
 \r
-    private final static String TAG = "FileSyncAdapter"; \r
-    \r
-    /*  Commented code for ugly performance tests\r
-    private final static int MAX_DELAYS = 100;\r
-    private static long[] mResponseDelays = new long[MAX_DELAYS]; \r
-    private static long[] mSaveDelays = new long[MAX_DELAYS];\r
-    private int mDelaysIndex = 0;\r
-    private int mDelaysCount = 0;\r
-    */\r
+    private final static String TAG = "FileSyncAdapter";\r
+\r
+    /** \r
+     * Maximum number of failed folder synchronizations that are supported before finishing the synchronization operation\r
+     */\r
+    private static final int MAX_FAILED_RESULTS = 3; \r
     \r
     private long mCurrentSyncTime;\r
     private boolean mCancellation;\r
-    private Account mAccount;\r
+    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
             SyncResult syncResult) {\r
 \r
         mCancellation = false;\r
-        mAccount = account;\r
-        \r
-        this.setAccount(mAccount);\r
+        mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);\r
+        mFailedResultsCounter = 0;\r
+        mLastFailedResult = null;\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(mAccount,\r
-                getContentProvider()));\r
-        \r
-        /*  Commented code for ugly performance tests\r
-        mDelaysIndex = 0;\r
-        mDelaysCount = 0;\r
-        */\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, "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
-        Log.d(TAG, "syncing owncloud account " + mAccount.name);\r
-\r
-        sendStickyBroadcast(true, null);  // message to signal the start to the UI\r
-\r
-        PropFindMethod query = null;\r
         try {\r
+            updateOCVersion();\r
             mCurrentSyncTime = System.currentTimeMillis();\r
-            query = new PropFindMethod(getUri().toString() + "/");\r
-            getClient().executeMethod(query);\r
-            MultiStatus resp = null;\r
-            resp = query.getResponseBodyAsMultiStatus();\r
-\r
-            if (resp.getResponses().length > 0) {\r
-                WebdavEntry we = new WebdavEntry(resp.getResponses()[0], getUri().getPath());\r
-                OCFile file = fillOCFile(we);\r
-                file.setParentId(0);\r
-                getStorageManager().saveFile(file);\r
-                if (!mCancellation) {\r
-                    fetchData(getUri().toString(), syncResult, file.getFileId());\r
-                }\r
+            if (!mCancellation) {\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
-        } catch (OperationCanceledException e) {\r
-            e.printStackTrace();\r
-        } catch (AuthenticatorException e) {\r
-            syncResult.stats.numAuthExceptions++;\r
-            e.printStackTrace();\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            e.printStackTrace();\r
-        } catch (DavException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            e.printStackTrace();\r
-        } catch (Throwable t) {\r
-            // TODO update syncResult\r
-            Log.e(TAG, "problem while synchronizing owncloud account " + account.name, t);\r
-            t.printStackTrace();\r
+            \r
             \r
         } finally {\r
-            if (query != null)\r
-                query.releaseConnection();  // let the connection available for other methods\r
-        }\r
-        \r
-        /*  Commented code for ugly performance tests\r
-        long sum = 0, mean = 0, max = 0, min = Long.MAX_VALUE;\r
-        for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
-            sum += mResponseDelays[i];\r
-            max = Math.max(max, mResponseDelays[i]);\r
-            min = Math.min(min, mResponseDelays[i]);\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
+                mSyncResult.tooManyRetries = true;\r
+                \r
+                /// notify the user about the failure of MANUAL synchronization\r
+                notifyFailedSynchronization();\r
+            }\r
+            sendStickyBroadcast(false, null, mLastFailedResult);        // message to signal the end to the UI\r
         }\r
-        mean = sum / mDelaysCount;\r
-        Log.e(TAG, "SYNC STATS - response: mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
         \r
-        sum = 0; max = 0; min = Long.MAX_VALUE;\r
-        for (int i=0; i<MAX_DELAYS && i<mDelaysCount; i++) {\r
-            sum += mSaveDelays[i];\r
-            max = Math.max(max, mSaveDelays[i]);\r
-            min = Math.min(min, mSaveDelays[i]);\r
+    }\r
+    \r
+    \r
+    \r
+    /**\r
+     * Called by system SyncManager when a synchronization is required to be cancelled.\r
+     * \r
+     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder\r
+     * fetched will be still saved in the database. See onPerformSync implementation.\r
+     */\r
+    @Override\r
+    public void onSyncCanceled() {\r
+        Log.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");\r
+        mCancellation = true;\r
+        super.onSyncCanceled();\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Updates the locally stored version value of the ownCloud server\r
+     */\r
+    private void updateOCVersion() {\r
+        UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());\r
+        RemoteOperationResult result = update.execute(getClient());\r
+        if (!result.isSuccess()) {\r
+            mLastFailedResult = result; \r
         }\r
-        mean = sum / mDelaysCount;\r
-        Log.e(TAG, "SYNC STATS - save:     mean time = " + mean + " ; max time = " + max + " ; min time = " + min);\r
-        Log.e(TAG, "SYNC STATS - folders measured: " + mDelaysCount);\r
-        */\r
-        \r
-        sendStickyBroadcast(false, null);        \r
     }\r
 \r
-    private void fetchData(String uri, SyncResult syncResult, long parentId) {\r
-        PropFindMethod query = null;\r
-        try {\r
-            Log.d(TAG, "fetching " + uri);\r
-            \r
-            // remote request \r
-            query = new PropFindMethod(uri);\r
-            /*  Commented code for ugly performance tests\r
-            long responseDelay = System.currentTimeMillis();\r
-            */\r
-            getClient().executeMethod(query);\r
-            /*  Commented code for ugly performance tests\r
-            responseDelay = System.currentTimeMillis() - responseDelay;\r
-            Log.e(TAG, "syncing: RESPONSE TIME for " + uri + " contents, " + responseDelay + "ms");\r
-            */\r
-            MultiStatus resp = null;\r
-            resp = query.getResponseBodyAsMultiStatus();\r
+    \r
+    \r
+    /**\r
+     * Synchronize the properties of files and folders contained in a remote folder given by remotePath.\r
+     * \r
+     * @param remotePath        Remote path to the folder to synchronize.\r
+     * @param parentId          Database Id of the folder to synchronize.\r
+     */\r
+    private void fetchData(String remotePath, long parentId) {\r
+        \r
+        if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult))\r
+            return;\r
+        \r
+        // perform folder synchronization\r
+        SynchronizeFolderOperation synchFolderOp = new SynchronizeFolderOperation(  remotePath, \r
+                                                                                    mCurrentSyncTime, \r
+                                                                                    parentId, \r
+                                                                                    getStorageManager(), \r
+                                                                                    getAccount(), \r
+                                                                                    getContext()\r
+                                                                                  );\r
+        RemoteOperationResult result = synchFolderOp.execute(getClient());\r
+        \r
+        \r
+        // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess\r
+        sendStickyBroadcast(true, remotePath, null);\r
+        \r
+        if (result.isSuccess()) {\r
+            // synchronize children folders \r
+            List<OCFile> children = synchFolderOp.getChildren();\r
+            fetchChildren(children);    // beware of the 'hidden' recursion here!\r
             \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
+//<<<<<<< HEAD
+        } else {\r
+            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {\r
+                mSyncResult.stats.numAuthExceptions++;\r
+                \r
+            } else if (result.getException() instanceof DavException) {\r
+                mSyncResult.stats.numParseExceptions++;\r
+                \r
+            } else if (result.getException() instanceof IOException) { \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
-                    Intent intent = new Intent(this.getContext(), FileDownloader.class);\r
-                    intent.putExtra(FileDownloader.EXTRA_ACCOUNT, getAccount());\r
-                    intent.putExtra(FileDownloader.EXTRA_FILE_PATH, file.getRemotePath());\r
-                    intent.putExtra(FileDownloader.EXTRA_REMOTE_PATH, file.getRemotePath());\r
-                    intent.putExtra(FileDownloader.EXTRA_FILE_SIZE, file.getFileLength());\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
+                        // 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
-                //Log.v(TAG, "adding file: " + file);\r
-                updatedFiles.add(file);\r
-                if (parentId == 0)\r
-                    parentId = file.getFileId();\r
-            }\r
-            /*  Commented code for ugly performance tests\r
-            long saveDelay = System.currentTimeMillis();\r
-            */            \r
-            getStorageManager().saveFiles(updatedFiles);    // all "at once" ; trying to get a best performance in database update\r
-            /*  Commented code for ugly performance tests\r
-            saveDelay = System.currentTimeMillis() - saveDelay;\r
-            Log.e(TAG, "syncing: SAVE TIME for " + uri + " contents, " + mSaveDelays[mDelaysIndex] + "ms");\r
-            */\r
-            \r
-            // removal of obsolete files\r
-            Vector<OCFile> files = getStorageManager().getDirectoryContent(\r
-                    getStorageManager().getFileById(parentId));\r
-            OCFile file;\r
-            String currentSavePath = FileDownloader.getSavePath(mAccount.name);\r
-            for (int i=0; i < files.size(); ) {\r
-                file = files.get(i);\r
-                if (file.getLastSyncDate() != mCurrentSyncTime) {\r
-                    Log.v(TAG, "removing file: " + file);\r
-                    getStorageManager().removeFile(file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));\r
-                    files.remove(i);\r
-                } else {\r
-                    i++;\r
-                }\r
             }\r
+            mFailedResultsCounter++;\r
+            mLastFailedResult = result;\r
+        }\r
             \r
-            // synchronized folder -> notice to UI\r
-            sendStickyBroadcast(true, getStorageManager().getFileById(parentId).getRemotePath());\r
-\r
-            // recursive fetch\r
-            for (int i=0; i < files.size() && !mCancellation; i++) {\r
-                OCFile newFile = files.get(i);\r
-                if (newFile.getMimetype().equals("DIR")) {\r
-                    fetchData(getUri().toString() + WebdavUtils.encodePath(newFile.getRemotePath()), syncResult, newFile.getFileId());\r
-                }\r
-            }\r
-            if (mCancellation) Log.d(TAG, "Leaving " + uri + " because cancelation request");\r
-                \r
-            /*  Commented code for ugly performance tests\r
-            mResponseDelays[mDelaysIndex] = responseDelay;\r
-            mSaveDelays[mDelaysIndex] = saveDelay;\r
-            mDelaysCount++;\r
-            mDelaysIndex++;\r
-            if (mDelaysIndex >= MAX_DELAYS)\r
-                mDelaysIndex = 0;\r
-             */\r
+    }\r
 \r
-        } catch (OperationCanceledException e) {\r
-            e.printStackTrace();\r
-        } catch (AuthenticatorException e) {\r
-            syncResult.stats.numAuthExceptions++;\r
-            e.printStackTrace();\r
-        } catch (IOException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            e.printStackTrace();\r
-        } catch (DavException e) {\r
-            syncResult.stats.numIoExceptions++;\r
-            e.printStackTrace();\r
-        } catch (Throwable t) {\r
-            // TODO update syncResult\r
-            Log.e(TAG, "problem while synchronizing owncloud account " + mAccount.name, t);\r
-            t.printStackTrace();\r
-            \r
-        } finally {\r
-            if (query != null)\r
-                query.releaseConnection();  // let the connection available for other methods\r
+    /**\r
+     * Checks if a failed result should terminate the synchronization process immediately, according to\r
+     * OUR OWN POLICY\r
+     * \r
+     * @param   failedResult        Remote operation result to check.\r
+     * @return                      'True' if the result should immediately finish the synchronization\r
+     */\r
+    private boolean isFinisher(RemoteOperationResult failedResult) {\r
+        if  (failedResult != null) {\r
+            RemoteOperationResult.ResultCode code = failedResult.getCode();\r
+            return (code.equals(RemoteOperationResult.ResultCode.SSL_ERROR) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION) ||\r
+                    code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED));\r
         }\r
+        return false;\r
     }\r
 \r
-    private OCFile fillOCFile(WebdavEntry we) {\r
-        OCFile file = new OCFile(we.decodedPath());\r
-        file.setCreationTimestamp(we.createTimestamp());\r
-        file.setFileLength(we.contentLength());\r
-        file.setMimetype(we.contentType());\r
-        file.setModificationTimestamp(we.modifiedTimesamp());\r
-        file.setLastSyncDate(mCurrentSyncTime);\r
-        return file;\r
+    /**\r
+     * Synchronize data of folders in the list of received files\r
+     * \r
+     * @param files         Files to recursively fetch \r
+     */\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(), 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
     }\r
+\r
     \r
-    \r
-    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {\r
+    /**\r
+     * Sends a message to any application component interested in the progress of the synchronization.\r
+     * \r
+     * @param inProgress        'True' when the synchronization progress is not finished.\r
+     * @param dirRemotePath     Remote path of a folder that was just synchronized (with or without success)\r
+     */\r
+    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath, RemoteOperationResult result) {\r
         Intent i = new Intent(FileSyncService.SYNC_MESSAGE);\r
         i.putExtra(FileSyncService.IN_PROGRESS, inProgress);\r
         i.putExtra(FileSyncService.ACCOUNT_NAME, getAccount().name);\r
         if (dirRemotePath != null) {\r
             i.putExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH, dirRemotePath);\r
         }\r
+        if (result != null) {\r
+            i.putExtra(FileSyncService.SYNC_RESULT, result);\r
+        }\r
         getContext().sendStickyBroadcast(i);\r
     }\r
+\r
+    \r
     \r
     /**\r
-     * Called by system SyncManager when a synchronization is required to be cancelled.\r
-     * \r
-     * Sets the mCancellation flag to 'true'. THe synchronization will be stopped when before a new folder is fetched. Data of the last folder\r
-     * fetched will be still saved in the database. See onPerformSync implementation.\r
+     * Notifies the user about a failed synchronization through the status notification bar \r
      */\r
-    @Override\r
-    public void onSyncCanceled() {\r
-        Log.d(TAG, "Synchronization of " + mAccount.name + " has been requested to cancell");\r
-        mCancellation = true;\r
-        super.onSyncCanceled();\r
+    private void notifyFailedSynchronization() {\r
+        Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());\r
+        notification.flags |= Notification.FLAG_AUTO_CANCEL;\r
+        // TODO put something smart in the contentIntent below\r
+        notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);\r
+        notification.setLatestEventInfo(getContext().getApplicationContext(), \r
+                                        getContext().getString(R.string.sync_fail_ticker), \r
+                                        String.format(getContext().getString(R.string.sync_fail_content), getAccount().name), \r
+                                        notification.contentIntent);\r
+        ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(R.string.sync_fail_ticker, notification);\r
     }\r
 \r
+    \r
+\r
 }\r