make confirmation dialog more universal
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / syncadapter / FileSyncAdapter.java
index ad88068..d14151a 100644 (file)
-/* ownCloud Android client application
- *   Copyright (C) 2011  Bartek Przybylski
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 3 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package eu.alefzero.owncloud.syncadapter;
-
-import java.io.IOException;
-
-import org.apache.http.entity.StringEntity;
-
-import android.accounts.Account;
-import android.accounts.AuthenticatorException;
-import android.accounts.OperationCanceledException;
-import android.content.ContentProviderClient;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.SyncResult;
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.util.Log;
-import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;
-import eu.alefzero.webdav.HttpPropFind;
-import eu.alefzero.webdav.TreeNode;
-import eu.alefzero.webdav.TreeNode.NodeProperty;
-import eu.alefzero.webdav.WebdavUtils;
-
-/**
- * SyncAdapter implementation for syncing sample SyncAdapter contacts to the
- * platform ContactOperations provider.
- */
-public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
-       private static final String TAG = "FileSyncAdapter";
-
-       public FileSyncAdapter(Context context, boolean autoInitialize) {
-               super(context, autoInitialize);
-       }
-
-       @Override
-       public synchronized void onPerformSync(
-                       Account account, 
-                       Bundle extras, 
-                       String authority, 
-                       ContentProviderClient provider, 
-                       SyncResult syncResult) {
-
-               try {
-                       this.setAccount(account);
-                       this.setContentProvider(provider);
-
-                       HttpPropFind query = this.getBasicQuery();
-                       query.setEntity(new StringEntity(WebdavUtils.prepareXmlForPropFind()));
-                       TreeNode root = this.fireQuery(query);
-
-                       commitToDatabase(root, null);
-               } catch (OperationCanceledException e) {
-                       e.printStackTrace();
-               } catch (AuthenticatorException e) {
-                       syncResult.stats.numAuthExceptions++;
-                       e.printStackTrace();
-               } catch (IOException e) {
-                       syncResult.stats.numIoExceptions++;
-                       e.printStackTrace();
-               } catch (RemoteException e) {
-                       e.printStackTrace();
-               }
-       }
-
-       private void commitToDatabase(TreeNode root, String parentId) throws RemoteException {
-               for (TreeNode n : root.getChildList()) {
-                       Log.d(TAG, n.toString());
-                       ContentValues cv = new ContentValues();
-                       cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, n.getProperty(NodeProperty.CONTENT_LENGTH));
-                       cv.put(ProviderTableMeta.FILE_MODIFIED, n.getProperty(NodeProperty.LAST_MODIFIED_DATE));
-                       cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, n.getProperty(NodeProperty.RESOURCE_TYPE));
-                       cv.put(ProviderTableMeta.FILE_PARENT, parentId);
-
-                       String name = n.getProperty(NodeProperty.NAME),
-                                       path = n.getProperty(NodeProperty.PATH);
-                       Cursor c = this.getContentProvider().query(ProviderTableMeta.CONTENT_URI_FILE,
-                                       null,
-                                       ProviderTableMeta.FILE_NAME+"=? AND " + ProviderTableMeta.FILE_PATH + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
-                                       new String[]{name, path, this.getAccount().name},
-                                       null);
-                       if (c.moveToFirst()) {
-                               this.getContentProvider().update(ProviderTableMeta.CONTENT_URI,
-                                               cv,
-                                               ProviderTableMeta._ID+"=?",
-                                                               new String[]{c.getString(c.getColumnIndex(ProviderTableMeta._ID))});
-                               Log.d(TAG, "ID of: "+name+":"+c.getString(c.getColumnIndex(ProviderTableMeta._ID)));
-                       } else {
-                               cv.put(ProviderTableMeta.FILE_NAME, n.getProperty(NodeProperty.NAME));
-                               cv.put(ProviderTableMeta.FILE_PATH, n.getProperty(NodeProperty.PATH));
-                               cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, this.getAccount().name);
-                               Uri entry = this.getContentProvider().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
-                               Log.d(TAG, "Inserting new entry " + path + name);
-                               c = this.getContentProvider().query(entry, null, null, null, null);
-                               c.moveToFirst();
-                       }
-                       if (n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {
-                               commitToDatabase(n, c.getString(c.getColumnIndex(ProviderTableMeta._ID)));
-                       }
-               }
-               // clean removed files
-               String[] selection = new String[root.getChildList().size()+2];
-               selection[0] = this.getAccount().name;
-               selection[1] = parentId;
-               String qm = "";
-               for (int i = 2; i < selection.length-1; ++i) {
-                       qm += "?,";
-                       selection[i] = root.getChildList().get(i-2).getProperty(NodeProperty.NAME);
-               }
-               if (selection.length >= 3) {
-                       selection[selection.length-1] = root.getChildrenNames()[selection.length-3];
-                       qm += "?";
-               }
-               for (int i = 0; i < selection.length; ++i) {
-                       Log.d(TAG,selection[i]+"");
-               }
-               Log.d(TAG,"Removing files "+ parentId);
-               this.getContentProvider().delete(ProviderTableMeta.CONTENT_URI,
-                               ProviderTableMeta.FILE_ACCOUNT_OWNER+"=? AND " + ProviderTableMeta.FILE_PARENT + (parentId==null?" IS ":"=")+"? AND " + ProviderTableMeta.FILE_NAME + " NOT IN ("+qm+")",
-                               selection);
-       }
-}
+/* ownCloud Android client application\r
+ *   Copyright (C) 2011  Bartek Przybylski\r
+ *\r
+ *   This program is free software: you can redistribute it and/or modify\r
+ *   it under the terms of the GNU General Public License as published by\r
+ *   the Free Software Foundation, either version 3 of the License, or\r
+ *   (at your option) any later version.\r
+ *\r
+ *   This program is distributed in the hope that it will be useful,\r
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ *   GNU General Public License for more details.\r
+ *\r
+ *   You should have received a copy of the GNU General Public License\r
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.\r
+ *\r
+ */\r
+\r
+package eu.alefzero.owncloud.syncadapter;\r
+\r
+import java.io.IOException;\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 android.accounts.Account;\r
+import android.accounts.AuthenticatorException;\r
+import android.accounts.OperationCanceledException;\r
+import android.content.ContentProviderClient;\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.owncloud.datamodel.FileDataStorageManager;\r
+import eu.alefzero.owncloud.datamodel.OCFile;\r
+import eu.alefzero.owncloud.files.services.FileDownloader;\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
+ * platform ContactOperations provider.\r
+ * \r
+ * @author Bartek Przybylski\r
+ */\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
+    \r
+    private long mCurrentSyncTime;\r
+    private boolean mCancellation;\r
+    private Account mAccount;\r
+    \r
+    public FileSyncAdapter(Context context, boolean autoInitialize) {\r
+        super(context, autoInitialize);\r
+    }\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
+        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
+        \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;\r
+        try {\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
+            }\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
+        /*  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
+        }\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
+        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
+        try {\r
+            //Log.v(TAG, "syncing: fetching " + uri);\r
+            \r
+            // remote request \r
+            PropFindMethod 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
+            // 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
+                \r
+                //getStorageManager().saveFile(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
+            for (int i=0; i < files.size(); ) {\r
+                file = files.get(i);\r
+                if (file.getLastSyncDate() != mCurrentSyncTime && file.getLastSyncDate() != 0) {\r
+                    getStorageManager().removeFile(file);\r
+                    files.remove(i);\r
+                } else {\r
+                    i++;\r
+                }\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 cancellation 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
+\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
+    }\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
+    \r
+    \r
+    private void sendStickyBroadcast(boolean inProgress, String dirRemotePath) {\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
+        getContext().sendStickyBroadcast(i);\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 " + mAccount.name + " has been requested to cancell");\r
+        mCancellation = true;\r
+        super.onSyncCanceled();\r
+    }\r
+\r
+}\r