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