From: Bartek Przybylski Date: Sat, 4 Feb 2012 18:49:33 +0000 (+0100) Subject: ssl support for syncing X-Git-Tag: oc-android-1.4.3~487 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/8ec6915a58779eb43f1446100cb6fa477c206529?ds=sidebyside ssl support for syncing --- diff --git a/src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java b/src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java index 3c1caf95..e4bacf29 100644 --- a/src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java +++ b/src/eu/alefzero/owncloud/syncadapter/AbstractOwnCloudSyncAdapter.java @@ -15,8 +15,9 @@ * along with this program. If not, see . * */ -package eu.alefzero.owncloud.syncadapter; - + +package eu.alefzero.owncloud.syncadapter; + import java.io.IOException; import java.net.UnknownHostException; import java.util.Date; @@ -25,8 +26,6 @@ import java.util.LinkedList; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.impl.auth.BasicScheme; @@ -46,143 +45,139 @@ import android.text.TextUtils; import eu.alefzero.owncloud.authenticator.AccountAuthenticator; import eu.alefzero.webdav.HttpPropFind; import eu.alefzero.webdav.TreeNode; -import eu.alefzero.webdav.TreeNode.NodeProperty; +import eu.alefzero.webdav.WebdavClient; import eu.alefzero.webdav.WebdavUtils; - -/** - * Base SyncAdapter for OwnCloud - * Designed to be subclassed for the concreete SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc.. - * - * @author sassman - * - */ -public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter { - - private AccountManager accountManager; - private Account account; - private ContentProviderClient contentProvider; - private Date lastUpdated; - - private DefaultHttpClient client = null; - private HttpHost host; - - public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) { - super(context, autoInitialize); - this.setAccountManager(AccountManager.get(context)); - } - - public AccountManager getAccountManager() { - return accountManager; - } - - public void setAccountManager(AccountManager accountManager) { - this.accountManager = accountManager; - } - - public Account getAccount() { - return account; - } - - public void setAccount(Account account) { - this.account = account; - } - - public ContentProviderClient getContentProvider() { - return contentProvider; - } - - public void setContentProvider(ContentProviderClient contentProvider) { - this.contentProvider = contentProvider; - } - - public Date getLastUpdated() { - return lastUpdated; - } - - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } - - protected ConnectionKeepAliveStrategy getKeepAliveStrategy() { - return new ConnectionKeepAliveStrategy() { - public long getKeepAliveDuration(HttpResponse response, HttpContext context) { - // TODO: change keep alive straategy basing on response: ie forbidden/not found/etc - // should have keep alive 0 - // default return: 5s - return 5 * 1000; - } - }; - } - - protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException { - HttpPropFind query = new HttpPropFind(getUri().toString()); - query.setHeader("Content-type", "text/xml"); - query.setHeader("User-Agent", "Android-ownCloud"); - return query; - } - - protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException { - BasicHttpContext httpContext = new BasicHttpContext(); - BasicScheme basicAuth = new BasicScheme(); - httpContext.setAttribute("preemptive-auth", basicAuth); - - HttpResponse response = getClient().execute(this.host, query, httpContext); - return response; - } - - protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException { - HttpResponse response = fireRawRequest(query); - - TreeNode root = new TreeNode(); - root.setProperty(TreeNode.NodeProperty.NAME, "/"); - this.parseResponse(response, getUri(), getClient(), this.host, root.getChildList()); - return root; - } - - protected Uri getUri() { - return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL)); - } - - private DefaultHttpClient getClient() throws OperationCanceledException, AuthenticatorException, IOException { - if(this.client == null) { - String username = getAccount().name.split("@")[0]; - String password = this.getAccountManager().blockingGetAuthToken(getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true); - if (this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL) == null) { - throw new UnknownHostException(); - } - Uri uri = getUri(); - - int port = (uri.getPort() == -1) ? 80 : uri.getPort(); - this.client = new DefaultHttpClient(); - this.client.getCredentialsProvider().setCredentials( - new AuthScope(uri.getHost(), port), - new UsernamePasswordCredentials(username, password) - ); - this.client.setKeepAliveStrategy(this.getKeepAliveStrategy()); - this.host = new HttpHost(uri.getHost(), port, (uri.getScheme() == "https") ? "https" : "http"); - } - - return this.client; - } - - private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList insertList) throws IOException, OperationCanceledException, AuthenticatorException { - boolean skipFirst = true; - for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) { - String path = n.stripPathFromFilename(uri.getPath()); - if (skipFirst) { - skipFirst = false; - continue; - } - insertList.add(n); - - if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) && - n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) { - - HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/"); - HttpResponse response = fireRawRequest(method); - parseResponse(response, uri, client, targetHost, n.getChildList()); - } - } - } - +import eu.alefzero.webdav.TreeNode.NodeProperty; + +/** + * Base SyncAdapter for OwnCloud + * Designed to be subclassed for the concreete SyncAdapter, like ConcatsSync, CalendarSync, FileSync etc.. + * + * @author sassman + * + */ +public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter { + + private AccountManager accountManager; + private Account account; + private ContentProviderClient contentProvider; + private Date lastUpdated; + + private HttpHost mHost; + private WebdavClient mClient = null; + + public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) { + super(context, autoInitialize); + this.setAccountManager(AccountManager.get(context)); + } + + public AccountManager getAccountManager() { + return accountManager; + } + + public void setAccountManager(AccountManager accountManager) { + this.accountManager = accountManager; + } + + public Account getAccount() { + return account; + } + + public void setAccount(Account account) { + this.account = account; + } + + public ContentProviderClient getContentProvider() { + return contentProvider; + } + + public void setContentProvider(ContentProviderClient contentProvider) { + this.contentProvider = contentProvider; + } + + public Date getLastUpdated() { + return lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + protected ConnectionKeepAliveStrategy getKeepAliveStrategy() { + return new ConnectionKeepAliveStrategy() { + public long getKeepAliveDuration(HttpResponse response, HttpContext context) { + // TODO: change keep alive straategy basing on response: ie forbidden/not found/etc + // should have keep alive 0 + // default return: 5s + return 5 * 1000; + } + }; + } + + protected HttpPropFind getPropFindQuery() throws OperationCanceledException, AuthenticatorException, IOException { + HttpPropFind query = new HttpPropFind(getUri().toString()); + query.setHeader("Content-type", "text/xml"); + query.setHeader("User-Agent", "Android-ownCloud"); + return query; + } + + protected HttpResponse fireRawRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException { + BasicHttpContext httpContext = new BasicHttpContext(); + BasicScheme basicAuth = new BasicScheme(); + httpContext.setAttribute("preemptive-auth", basicAuth); + + HttpResponse response = getClient().execute(mHost, query, httpContext); + return response; + } + + protected TreeNode fireRequest(HttpRequest query) throws ClientProtocolException, OperationCanceledException, AuthenticatorException, IOException { + HttpResponse response = fireRawRequest(query); + + TreeNode root = new TreeNode(); + root.setProperty(TreeNode.NodeProperty.NAME, "/"); + this.parseResponse(response, getUri(), getClient(), mHost, root.getChildList()); + return root; + } + + protected Uri getUri() { + return Uri.parse(this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL)); + } + + private DefaultHttpClient getClient() throws OperationCanceledException, AuthenticatorException, IOException { + if(mClient == null) { + String username = getAccount().name.split("@")[0]; + String password = this.getAccountManager().blockingGetAuthToken(getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true); + if (this.getAccountManager().getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL) == null) { + throw new UnknownHostException(); + } + Uri uri = getUri(); + + mClient = new WebdavClient(uri); + mClient.setCredentials(username, password); + mClient.allowUnsignedCertificates(); + mHost = mClient.getTargetHost(); + } + + return mClient.getHttpClient(); + } + + private void parseResponse(HttpResponse resp, Uri uri, DefaultHttpClient client, HttpHost targetHost, LinkedList insertList) throws IOException, OperationCanceledException, AuthenticatorException { + boolean skipFirst = true; + for (TreeNode n :WebdavUtils.parseResponseToNodes(resp.getEntity().getContent())) { + String path = n.stripPathFromFilename(uri.getPath()); + if (skipFirst) { + skipFirst = false; + continue; + } + insertList.add(n); + + if (!TextUtils.isEmpty(n.getProperty(NodeProperty.NAME)) && + n.getProperty(NodeProperty.RESOURCE_TYPE).equals("DIR")) { + + HttpPropFind method = new HttpPropFind(uri.getPath() + path + n.getProperty(NodeProperty.NAME).replace(" ", "%20") + "/"); + HttpResponse response = fireRawRequest(method); + parseResponse(response, uri, client, targetHost, n.getChildList()); + } + } + } } \ No newline at end of file diff --git a/src/eu/alefzero/owncloud/ui/activity/LandingActivity.java b/src/eu/alefzero/owncloud/ui/activity/LandingActivity.java index b8f18781..2080790f 100644 --- a/src/eu/alefzero/owncloud/ui/activity/LandingActivity.java +++ b/src/eu/alefzero/owncloud/ui/activity/LandingActivity.java @@ -70,7 +70,6 @@ public class LandingActivity extends FragmentActivity implements OnClickListener return dialog; } - @Override public void onClick(DialogInterface dialog, int which) { // In any case - we won't need it anymore dialog.dismiss(); diff --git a/src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java b/src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java index 694225d5..e31c65fb 100644 --- a/src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java +++ b/src/eu/alefzero/owncloud/ui/adapter/LandingScreenAdapter.java @@ -53,12 +53,10 @@ public class LandingScreenAdapter extends BaseAdapter { mContext = context; } - @Override public int getCount() { return mLandingScreenIcons.length; } - @Override /** * Returns the Intent associated with this object * or null if the functionality is not yet implemented @@ -78,12 +76,10 @@ public class LandingScreenAdapter extends BaseAdapter { return intent; } - @Override public long getItemId(int position) { return position; } - @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflator = LayoutInflater.from(mContext); diff --git a/src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java b/src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java index dd7ca316..d431a4f2 100644 --- a/src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java +++ b/src/eu/alefzero/owncloud/ui/fragment/LandingPageFragment.java @@ -17,6 +17,7 @@ */ package eu.alefzero.owncloud.ui.fragment; +import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; @@ -24,11 +25,15 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; -import android.widget.AdapterView.OnItemClickListener; +import android.widget.BaseAdapter; import android.widget.GridView; +import android.widget.ImageView; +import android.widget.TextView; import android.widget.Toast; +import android.widget.AdapterView.OnItemClickListener; import eu.alefzero.owncloud.R; -import eu.alefzero.owncloud.ui.adapter.LandingScreenAdapter; +import eu.alefzero.owncloud.ui.activity.FileDisplayActivity; +import eu.alefzero.owncloud.ui.activity.Preferences; /** * Used on the Landing page to display what Components of @@ -55,7 +60,6 @@ public class LandingPageFragment extends Fragment implements OnItemClickListener grid.setOnItemClickListener(this); } - @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /* * Start an activity based on the selection @@ -64,10 +68,83 @@ public class LandingPageFragment extends Fragment implements OnItemClickListener Intent intent; intent = (Intent) parent.getAdapter().getItem(position); if(intent != null ){ - startActivity(intent); + startActivity(intent); } else { Toast toast = Toast.makeText(getActivity(), "Not yet implemented!", Toast.LENGTH_SHORT); toast.show(); + } + } + + /** + * Used to populate the landing page grid. + * Defined this one right in here as private class + * as it is unlikely that this Adapter can be useful + * anywhere else. + * + * @author Lennart Rosam + * + */ + private class LandingScreenAdapter extends BaseAdapter { + + private Context mContext; + + private final Integer[] mLandingScreenIcons = { R.drawable.home, + R.drawable.music, R.drawable.contacts, + android.R.drawable.ic_menu_today, + android.R.drawable.ic_menu_agenda, + android.R.drawable.ic_menu_preferences }; + + private final Integer[] mLandingScreenTexts = { R.string.main_files, + R.string.main_music, R.string.main_contacts, + R.string.main_calendar, R.string.main_bookmarks, + R.string.main_settings }; + + public LandingScreenAdapter(Context context) { + mContext = context; + } + + public int getCount() { + return mLandingScreenIcons.length; + } + + /** + * Returns the Intent associated with this object + * or null if the functionality is not yet implemented + */ + public Object getItem(int position) { + Intent intent = new Intent(); + switch (position) { + case 0: + intent.setClass(mContext, FileDisplayActivity.class); + break; + case 5: + intent.setClass(mContext, Preferences.class); + break; + default: + intent = null; + } + return intent; + } + + public long getItemId(int position) { + return position; + } + + public View getView(int position, View convertView, ViewGroup parent) { + if (convertView == null) { + LayoutInflater inflator = LayoutInflater.from(mContext); + convertView = inflator + .inflate(R.layout.landing_page_item, null); + + ImageView icon = (ImageView) convertView + .findViewById(R.id.gridImage); + TextView iconText = (TextView) convertView + .findViewById(R.id.gridText); + + icon.setImageResource(mLandingScreenIcons[position]); + iconText.setText(mLandingScreenTexts[position]); + } + return convertView; } } diff --git a/src/eu/alefzero/webdav/WebdavClient.java b/src/eu/alefzero/webdav/WebdavClient.java index 4d97ceb3..722614ee 100644 --- a/src/eu/alefzero/webdav/WebdavClient.java +++ b/src/eu/alefzero/webdav/WebdavClient.java @@ -15,182 +15,181 @@ * along with this program. If not, see . * */ -package eu.alefzero.webdav; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; - -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.HttpVersion; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.params.ConnManagerPNames; -import org.apache.http.conn.params.ConnPerRouteBean; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.entity.FileEntity; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.BasicHttpContext; - -import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory; - -import android.net.Uri; -import android.util.Log; - -/** - * A basic WebDAV-Client - * @author Bartek Przybylski - * - */ -public class WebdavClient { - private DefaultHttpClient mHttpClient; - private BasicHttpContext mHttpContext; - private HttpHost mTargetHost; - private SchemeRegistry mSchemeRegistry; - private Uri mUri; - final private static String TAG = "WebdavClient"; - - public WebdavClient(Uri uri) { - mUri = uri; - mSchemeRegistry = new SchemeRegistry(); - setupHttpClient(); - } - - public void setCredentials(String username, String password) { - // determine default port for http or https - int targetPort = mTargetHost.getPort() == -1 ? - ( mUri.getScheme().equals("https") ? 443 : 80) - : mUri.getPort(); - - mHttpClient.getCredentialsProvider().setCredentials( - new AuthScope(mUri.getHost(), targetPort), - new UsernamePasswordCredentials(username, password)); - BasicScheme basicAuth = new BasicScheme(); - mHttpContext.setAttribute("preemptive-auth", basicAuth); - } - - public void allowUnsignedCertificates() { - // https - mSchemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); - } - - public boolean downloadFile(String filepath, File targetPath) { - HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ", "%20")); - get.setHeader("Host", mUri.getHost()); - get.setHeader("User-Agent", "Android-ownCloud"); - - try { - HttpResponse response = mHttpClient.execute(mTargetHost, get, mHttpContext); - if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { - return false; - } - BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent()); - FileOutputStream fos = new FileOutputStream(targetPath); - - byte[] bytes = new byte[512]; - int readResult; - while ((readResult = bis.read(bytes)) != -1) fos.write(bytes, 0, readResult); - - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - void getFileList(String dirPath) { - - } - - public boolean putFile(String localFile, - String remoteTarget, - String contentType) { - boolean result = true; - HttpPut method = new HttpPut(mUri.toString() + remoteTarget.replace(" ", "%20")); - method.setHeader("Content-type", contentType); - method.setHeader("Host", mUri.getHost()); - method.setHeader("User-Agent", "Android-ownCloud"); - - try { - FileBody fb = new FileBody(new File(localFile, contentType)); - final FileEntity fileEntity = new FileEntity(new File(localFile), contentType); - - method.setEntity(fileEntity); - Log.i(TAG, "executing:" + method.getRequestLine().toString()); - - mHttpClient.execute(mTargetHost, method, mHttpContext); - /*mHandler.post(new Runnable() { - public void run() { - Uploader.this.PartialupdateUpload(c.getString(c.getColumnIndex(Media.DATA)), - c.getString(c.getColumnIndex(Media.DISPLAY_NAME)), - mUploadPath + (mUploadPath.equals("/")?"":"/"), - fileEntity.getContentType().getValue(), - fileEntity.getContentLength()+""); - } - }); - Log.i(TAG, "Uploading, done"); -*/ - Log.i(TAG, "Uploading, done"); - } catch (final Exception e) { - Log.i(TAG, ""+e.getMessage()); - result = false; - } - - return result; - } - - public boolean createDirectory(String path) { - HttpMkCol method = new HttpMkCol(mUri.toString() + path + "/"); - method.setHeader("User-Agent", "Android-ownCloud"); - - try { - mHttpClient.execute(mTargetHost, method, mHttpContext); - Log.i(TAG, "Creating dir completed"); - } catch (final Exception e) { - e.printStackTrace(); - return false; - } - return true; - } - - private void setupHttpClient() { - // http scheme - mSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); - mSchemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); - - HttpParams params = new BasicHttpParams(); - params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); - params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); - params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); - HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); - - mHttpContext = new BasicHttpContext(); - ClientConnectionManager cm = new ThreadSafeClientConnManager(params, mSchemeRegistry); - - int port = mUri.getPort() == -1 ? - mUri.getScheme().equals("https") ? 443 : 80 - : mUri.getPort(); - - mTargetHost = new HttpHost(mUri.getHost(), port, mUri.getScheme()); - - mHttpClient = new DefaultHttpClient(cm, params); - } -} +package eu.alefzero.webdav; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.HttpVersion; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.params.ConnManagerPNames; +import org.apache.http.conn.params.ConnPerRouteBean; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.entity.FileEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.BasicHttpContext; + +import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory; +import eu.alefzero.webdav.HttpMkCol; + +import android.net.Uri; +import android.util.Log; + +public class WebdavClient { + private DefaultHttpClient mHttpClient; + private BasicHttpContext mHttpContext; + private HttpHost mTargetHost; + private SchemeRegistry mSchemeRegistry; + private Uri mUri; + final private static String TAG = "WebdavClient"; + + public DefaultHttpClient getHttpClient() { + return mHttpClient; + } + public HttpHost getTargetHost() { + return mTargetHost; + } + + public WebdavClient(Uri uri) { + mUri = uri; + mSchemeRegistry = new SchemeRegistry(); + setupHttpClient(); + } + + public void setCredentials(String username, String password) { + // determine default port for http or https + int targetPort = mTargetHost.getPort() == -1 ? + ( mUri.getScheme().equals("https") ? 443 : 80) + : mUri.getPort(); + + mHttpClient.getCredentialsProvider().setCredentials( + new AuthScope(mUri.getHost(), targetPort), + new UsernamePasswordCredentials(username, password)); + BasicScheme basicAuth = new BasicScheme(); + mHttpContext.setAttribute("preemptive-auth", basicAuth); + } + + public void allowUnsignedCertificates() { + // https + mSchemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); + } + + public boolean downloadFile(String filepath, File targetPath) { + HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ", "%20")); + get.setHeader("Host", mUri.getHost()); + get.setHeader("User-Agent", "Android-ownCloud"); + + try { + HttpResponse response = mHttpClient.execute(mTargetHost, get, mHttpContext); + if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { + return false; + } + BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent()); + FileOutputStream fos = new FileOutputStream(targetPath); + + byte[] bytes = new byte[512]; + int readResult; + while ((readResult = bis.read(bytes)) != -1) fos.write(bytes, 0, readResult); + + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + public boolean putFile(String localFile, + String remoteTarget, + String contentType) { + boolean result = true; + HttpPut method = new HttpPut(mUri.toString() + remoteTarget.replace(" ", "%20")); + method.setHeader("Content-type", contentType); + method.setHeader("Host", mUri.getHost()); + method.setHeader("User-Agent", "Android-ownCloud"); + + try { + FileBody fb = new FileBody(new File(localFile, contentType)); + final FileEntity fileEntity = new FileEntity(new File(localFile), contentType); + + method.setEntity(fileEntity); + Log.i(TAG, "executing:" + method.getRequestLine().toString()); + + mHttpClient.execute(mTargetHost, method, mHttpContext); + /*mHandler.post(new Runnable() { + public void run() { + Uploader.this.PartialupdateUpload(c.getString(c.getColumnIndex(Media.DATA)), + c.getString(c.getColumnIndex(Media.DISPLAY_NAME)), + mUploadPath + (mUploadPath.equals("/")?"":"/"), + fileEntity.getContentType().getValue(), + fileEntity.getContentLength()+""); + } + }); + Log.i(TAG, "Uploading, done"); +*/ + Log.i(TAG, "Uploading, done"); + } catch (final Exception e) { + Log.i(TAG, ""+e.getMessage()); + result = false; + } + + return result; + } + + public boolean createDirectory(String path) { + HttpMkCol method = new HttpMkCol(mUri.toString() + path + "/"); + method.setHeader("User-Agent", "Android-ownCloud"); + + try { + mHttpClient.execute(mTargetHost, method, mHttpContext); + Log.i(TAG, "Creating dir completed"); + } catch (final Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + private void setupHttpClient() { + // http scheme + mSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + mSchemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); + + HttpParams params = new BasicHttpParams(); + params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); + params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); + params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); + HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); + + mHttpContext = new BasicHttpContext(); + ClientConnectionManager cm = new ThreadSafeClientConnManager(params, mSchemeRegistry); + + int port = mUri.getPort() == -1 ? + mUri.getScheme().equals("https") ? 443 : 80 + : mUri.getPort(); + + mTargetHost = new HttpHost(mUri.getHost(), port, mUri.getScheme()); + + mHttpClient = new DefaultHttpClient(cm, params); + } +}