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