3c1caf954495c283c5c0aa60cbd4e78716f8f417
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / syncadapter / AbstractOwnCloudSyncAdapter.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package eu.alefzero.owncloud.syncadapter;
19
20 import java.io.IOException;
21 import java.net.UnknownHostException;
22 import java.util.Date;
23 import java.util.LinkedList;
24
25 import org.apache.http.HttpHost;
26 import org.apache.http.HttpRequest;
27 import org.apache.http.HttpResponse;
28 import org.apache.http.auth.AuthScope;
29 import org.apache.http.auth.UsernamePasswordCredentials;
30 import org.apache.http.client.ClientProtocolException;
31 import org.apache.http.conn.ConnectionKeepAliveStrategy;
32 import org.apache.http.impl.auth.BasicScheme;
33 import org.apache.http.impl.client.DefaultHttpClient;
34 import org.apache.http.protocol.BasicHttpContext;
35 import org.apache.http.protocol.HttpContext;
36
37 import android.accounts.Account;
38 import android.accounts.AccountManager;
39 import android.accounts.AuthenticatorException;
40 import android.accounts.OperationCanceledException;
41 import android.content.AbstractThreadedSyncAdapter;
42 import android.content.ContentProviderClient;
43 import android.content.Context;
44 import android.net.Uri;
45 import android.text.TextUtils;
46 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
47 import eu.alefzero.webdav.HttpPropFind;
48 import eu.alefzero.webdav.TreeNode;
49 import eu.alefzero.webdav.TreeNode.NodeProperty;
50 import eu.alefzero.webdav.WebdavUtils;
51
52 /**
53 * Base SyncAdapter for OwnCloud
54 * Designed to be subclassed for the concreete SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc..
55 *
56 * @author sassman
57 *
58 */
59 public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter {
60
61 private AccountManager accountManager;
62 private Account account;
63 private ContentProviderClient contentProvider;
64 private Date lastUpdated;
65
66 private DefaultHttpClient client = null;
67 private HttpHost host;
68
69 public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {
70 super(context, autoInitialize);
71 this.setAccountManager(AccountManager.get(context));
72 }
73
74 public AccountManager getAccountManager() {
75 return accountManager;
76 }
77
78 public void setAccountManager(AccountManager accountManager) {
79 this.accountManager = accountManager;
80 }
81
82 public Account getAccount() {
83 return account;
84 }
85
86 public void setAccount(Account account) {
87 this.account = account;
88 }
89
90 public ContentProviderClient getContentProvider() {
91 return contentProvider;
92 }
93
94 public void setContentProvider(ContentProviderClient contentProvider) {
95 this.contentProvider = contentProvider;
96 }
97
98 public Date getLastUpdated() {
99 return lastUpdated;
100 }
101
102 public void setLastUpdated(Date lastUpdated) {
103 this.lastUpdated = lastUpdated;
104 }
105
106 protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {
107 return new ConnectionKeepAliveStrategy() {
108 public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
109 // TODO: change keep alive straategy basing on response: ie forbidden/not found/etc
110 // should have keep alive 0
111 // default return: 5s
112 return 5 * 1000;
113 }
114 };
115 }
116
117 protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException {
118 HttpPropFind query = new HttpPropFind(getUri().toString());
119 query.setHeader("Content-type", "text/xml");
120 query.setHeader("User-Agent", "Android-ownCloud");
121 return query;
122 }
123
124 protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
125 BasicHttpContext httpContext = new BasicHttpContext();
126 BasicScheme basicAuth = new BasicScheme();
127 httpContext.setAttribute("preemptive-auth", basicAuth);
128
129 HttpResponse response = getClient().execute(this.host, query, httpContext);
130 return response;
131 }
132
133 protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException {
134 HttpResponse response = fireRawRequest(query);
135
136 TreeNode root = new TreeNode();
137 root.setProperty(TreeNode.NodeProperty.NAME, "/");
138 this.parseResponse(response, getUri(), getClient(), this.host, root.getChildList());
139 return root;
140 }
141
142 protected Uri getUri() {
143 return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL));
144 }
145
146 private DefaultHttpClient getClient() throws OperationCanceledException, AuthenticatorException, IOException {
147 if(this.client == null) {
148 String username = getAccount().name.split("@")[0];
149 String password = this.getAccountManager().blockingGetAuthToken(getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);
150 if (this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL) == null) {
151 throw new UnknownHostException();
152 }
153 Uri uri = getUri();
154
155 int port = (uri.getPort() == -1) ? 80 : uri.getPort();
156 this.client = new DefaultHttpClient();
157 this.client.getCredentialsProvider().setCredentials(
158 new AuthScope(uri.getHost(), port),
159 new UsernamePasswordCredentials(username, password)
160 );
161 this.client.setKeepAliveStrategy(this.getKeepAliveStrategy());
162 this.host = new HttpHost(uri.getHost(), port, (uri.getScheme() == "https") ? "https" : "http");
163 }
164
165 return this.client;
166 }
167
168 private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList<TreeNode> insertList) throws IOException, OperationCanceledException, AuthenticatorException {
169 boolean skipFirst = true;
170 for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) {
171 String path = n.stripPathFromFilename(uri.getPath());
172 if (skipFirst) {
173 skipFirst = false;
174 continue;
175 }
176 insertList.add(n);
177
178 if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) &&
179 n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) {
180
181 HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/");
182 HttpResponse response = fireRawRequest(method);
183 parseResponse(response, uri, client, targetHost, n.getChildList());
184 }
185 }
186 }
187
188 }