Fixed navigation behavior
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / syncadapter / AbstractOwnCloudSyncAdapter.java
index 3c1caf9..41a0503 100644 (file)
@@ -15,6 +15,7 @@
  *   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
@@ -25,8 +26,6 @@ import java.util.LinkedList;
 import org.apache.http.HttpHost;\r
 import org.apache.http.HttpRequest;\r
 import org.apache.http.HttpResponse;\r
-import org.apache.http.auth.AuthScope;\r
-import org.apache.http.auth.UsernamePasswordCredentials;\r
 import org.apache.http.client.ClientProtocolException;\r
 import org.apache.http.conn.ConnectionKeepAliveStrategy;\r
 import org.apache.http.impl.auth.BasicScheme;\r
@@ -43,28 +42,33 @@ import android.content.ContentProviderClient;
 import android.content.Context;\r
 import android.net.Uri;\r
 import android.text.TextUtils;\r
+import android.util.Log;\r
 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;\r
+import eu.alefzero.owncloud.datamodel.OCFile;\r
 import eu.alefzero.webdav.HttpPropFind;\r
 import eu.alefzero.webdav.TreeNode;\r
 import eu.alefzero.webdav.TreeNode.NodeProperty;\r
+import eu.alefzero.webdav.WebdavClient;\r
 import eu.alefzero.webdav.WebdavUtils;\r
 \r
 /**\r
- * Base SyncAdapter for OwnCloud\r
- * Designed to be subclassed for the concreete SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc..\r
+ * Base SyncAdapter for OwnCloud Designed to be subclassed for the concrete\r
+ * SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc..\r
  * \r
  * @author sassman\r
- *\r
+ * \r
  */\r
-public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter {\r
+public abstract class AbstractOwnCloudSyncAdapter extends\r
+               AbstractThreadedSyncAdapter {\r
 \r
        private AccountManager accountManager;\r
        private Account account;\r
        private ContentProviderClient contentProvider;\r
        private Date lastUpdated;\r
-       \r
-       private DefaultHttpClient client = null;\r
-       private HttpHost host;\r
+\r
+       private HttpHost mHost;\r
+       private WebdavClient mClient = null;\r
+       private static String TAG = "AbstractOwnCloudSyncAdapter";\r
 \r
        public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {\r
                super(context, autoInitialize);\r
@@ -102,87 +106,141 @@ public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAd
        public void setLastUpdated(Date lastUpdated) {\r
                this.lastUpdated = lastUpdated;\r
        }\r
-       \r
+\r
        protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {\r
                return new ConnectionKeepAliveStrategy() {\r
-                       public long getKeepAliveDuration(HttpResponse response, HttpContext context) {\r
-                               // TODO: change keep alive straategy basing on response: ie forbidden/not found/etc\r
+                       public long getKeepAliveDuration(HttpResponse response,\r
+                                       HttpContext context) {\r
+                               // Change keep alive straategy basing on response: ie\r
+                               // forbidden/not found/etc\r
                                // should have keep alive 0\r
                                // default return: 5s\r
+                               int statusCode = response.getStatusLine().getStatusCode();\r
+\r
+                               // HTTP 400, 500 Errors as well as HTTP 118 - Connection timed\r
+                               // out\r
+                               if ((statusCode >= 400 && statusCode <= 418)\r
+                                               || (statusCode >= 421 && statusCode <= 426)\r
+                                               || (statusCode >= 500 && statusCode <= 510)\r
+                                               || statusCode == 118) {\r
+                                       return 0;\r
+                               }\r
+\r
                                return 5 * 1000;\r
                        }\r
                };\r
        }\r
-       \r
-       protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException {\r
+\r
+       protected HttpPropFind getPropFindQuery()\r
+                       throws OperationCanceledException, AuthenticatorException,\r
+                       IOException {\r
                HttpPropFind query = new HttpPropFind(getUri().toString());\r
                query.setHeader("Content-type", "text/xml");\r
                query.setHeader("User-Agent", "Android-ownCloud");\r
                return query;\r
        }\r
-       \r
-       protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {\r
-           BasicHttpContext httpContext = new BasicHttpContext();\r
-        BasicScheme basicAuth = new BasicScheme();\r
-        httpContext.setAttribute("preemptive-auth", basicAuth);\r
-        \r
-        HttpResponse response = getClient().execute(this.host, query, httpContext);\r
-        return response;\r
-       }\r
-       \r
-       protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {\r
+\r
+       protected HttpResponse fireRawRequest(HttpRequest query)\r
+                       throws ClientProtocolException, OperationCanceledException,\r
+                       AuthenticatorException, IOException {\r
+               BasicHttpContext httpContext = new BasicHttpContext();\r
+               BasicScheme basicAuth = new BasicScheme();\r
+               httpContext.setAttribute("preemptive-auth", basicAuth);\r
+\r
+               HttpResponse response = getClient().execute(mHost, query, httpContext);\r
+               return response;\r
+       }\r
+\r
+       protected TreeNode fireRequest(HttpRequest query)\r
+                       throws ClientProtocolException, OperationCanceledException,\r
+                       AuthenticatorException, IOException {\r
                HttpResponse response = fireRawRequest(query);\r
-               \r
+\r
                TreeNode root = new TreeNode();\r
-               root.setProperty(TreeNode.NodeProperty.NAME, "/");\r
-               this.parseResponse(response, getUri(), getClient(), this.host, root.getChildList());\r
+               root.setProperty(TreeNode.NodeProperty.NAME, "");\r
+               this.parseResponse(response, getUri(), getClient(), mHost,\r
+                               root.getChildList(), false, 0);\r
                return root;\r
        }\r
-       \r
+\r
        protected Uri getUri() {\r
-               return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL));\r
+               return Uri.parse(this.getAccountManager().getUserData(getAccount(),\r
+                               AccountAuthenticator.KEY_OC_URL));\r
        }\r
-       \r
-       private DefaultHttpClient getClient() throws OperationCanceledException, AuthenticatorException, IOException {\r
-               if(this.client == null) {\r
+\r
+       private DefaultHttpClient getClient() throws OperationCanceledException,\r
+                       AuthenticatorException, IOException {\r
+               if (mClient == null) {\r
                        String username = getAccount().name.split("@")[0];\r
-                       String password = this.getAccountManager().blockingGetAuthToken(getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
-                       if (this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL) == null) {\r
+                       String password = this.getAccountManager().blockingGetAuthToken(\r
+                                       getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
+                       if (this.getAccountManager().getUserData(getAccount(),\r
+                                       AccountAuthenticator.KEY_OC_URL) == null) {\r
                                throw new UnknownHostException();\r
                        }\r
                        Uri uri = getUri();\r
-       \r
-                       int port = (uri.getPort() == -1) ? 80 : uri.getPort();\r
-                       this.client = new DefaultHttpClient();\r
-                       this.client.getCredentialsProvider().setCredentials(\r
-                               new AuthScope(uri.getHost(), port),\r
-                               new UsernamePasswordCredentials(username, password)\r
-                       );\r
-                       this.client.setKeepAliveStrategy(this.getKeepAliveStrategy());\r
-                       this.host = new HttpHost(uri.getHost(), port, (uri.getScheme() == "https") ? "https" : "http");\r
+\r
+                       mClient = new WebdavClient(uri);\r
+                       mClient.setCredentials(username, password);\r
+                       mClient.allowUnsignedCertificates();\r
+                       mHost = mClient.getTargetHost();\r
                }\r
-               \r
-               return this.client;\r
+\r
+               return mClient.getHttpClient();\r
        }\r
-       \r
-       private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList<TreeNode> insertList) throws IOException, OperationCanceledException, AuthenticatorException {\r
-               boolean skipFirst = true;\r
-               for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) {\r
-                       String path = n.stripPathFromFilename(uri.getPath());\r
+\r
+       private void parseResponse(HttpResponse resp, Uri uri,\r
+                       DefaultHttpClient client, HttpHost targetHost,\r
+                       LinkedList<TreeNode> insertList, boolean sf, long parent_id)\r
+                       throws IOException, OperationCanceledException,\r
+                       AuthenticatorException {\r
+               boolean skipFirst = sf, override_parent = !sf;\r
+               for (TreeNode n : WebdavUtils.parseResponseToNodes(resp.getEntity()\r
+                               .getContent())) {\r
                        if (skipFirst) {\r
                                skipFirst = false;\r
                                continue;\r
                        }\r
-                       insertList.add(n);\r
+                       String path = n.stripPathFromFilename(uri.getPath());\r
+\r
+                       long mod = n.getProperty(NodeProperty.LAST_MODIFIED_DATE) == null ? 0\r
+                                       : Long.parseLong(n\r
+                                                       .getProperty(NodeProperty.LAST_MODIFIED_DATE));\r
+                       OCFile file = new OCFile(getContentProvider(), getAccount(),\r
+                                       n.getProperty(NodeProperty.PATH));\r
+                       if (file.fileExists() && file.getModificationTimestamp() >= mod) {\r
+                               Log.d(TAG, "No update for file/dir " + file.getFileName()\r
+                                               + " is needed");\r
+                       } else {\r
+                               Log.d(TAG, "File " + n.getProperty(NodeProperty.PATH)\r
+                                               + " will be "\r
+                                               + (file.fileExists() ? "updated" : "created"));\r
+                               long len = n.getProperty(NodeProperty.CONTENT_LENGTH) == null ? 0\r
+                                               : Long.parseLong(n\r
+                                                               .getProperty(NodeProperty.CONTENT_LENGTH));\r
+                               long create = n.getProperty(NodeProperty.CREATE_DATE) == null ? 0\r
+                                               : Long.parseLong(n\r
+                                                               .getProperty(NodeProperty.CREATE_DATE));\r
+                               file = OCFile.createNewFile(getContentProvider(), getAccount(),\r
+                                               n.getProperty(NodeProperty.PATH), len, create, mod,\r
+                                               n.getProperty(NodeProperty.RESOURCE_TYPE), parent_id);\r
+                               file.save();\r
+                               if (override_parent) {\r
+                                       parent_id = file.getFileId();\r
+                                       override_parent = false;\r
+                               }\r
+                       }\r
+\r
+                       if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME))\r
+                                       && n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {\r
 \r
-                       if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) &&\r
-                                       n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {\r
-                           \r
-                           HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/");\r
+                               HttpPropFind method = new HttpPropFind(uri.getPath() + path\r
+                                               + n.getProperty(NodeProperty.NAME).replace(" ", "%20")\r
+                                               + "/");\r
                                HttpResponse response = fireRawRequest(method);\r
-                               parseResponse(response, uri, client, targetHost, n.getChildList());\r
+                               parseResponse(response, uri, client, targetHost,\r
+                                               n.getChildList(), true, file.getFileId());\r
                        }\r
                }\r
        }\r
-       \r
 }
\ No newline at end of file