/** * Creates a WebdavClient setup for an ownCloud account * * <p>Do not call this method from the main thread. * * @param account The ownCloud account * @param appContext Android application context * @return A WebdavClient object ready to be used * @throws AuthenticatorException If the authenticator failed to get the authorization token for * the account. * @throws OperationCanceledException If the authenticator operation was cancelled while getting * the authorization token for the account. * @throws IOException If there was some I/O error while getting the authorization token for the * account. * @throws AccountNotFoundException If 'account' is unknown for the AccountManager */ public static WebdavClient createOwnCloudClient(Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { // Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name); Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); AccountManager am = AccountManager.get(appContext); boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null; WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso); if (isOauth2) { String accessToken = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypeAccessToken(), false); client.setBearerCredentials( accessToken); // TODO not assume that the access token is a bearer token } else if (isSamlSso) { // TODO avoid a call to getUserData here String accessToken = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypeSamlSessionCookie(), false); client.setSsoSessionCookie(accessToken); } else { String username = account.name.substring(0, account.name.lastIndexOf('@')); // String password = am.getPassword(account); String password = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypePass(), false); client.setBasicCredentials(username, password); } return client; }
/** * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client * connections. * * @param uri URL to the ownCloud server * @param context Android context where the WebdavClient is being created. * @return A WebdavClient object ready to be used */ public static WebdavClient createOwnCloudClient( Uri uri, Context context, boolean followRedirects) { try { registerAdvancedSslContext(true, context); } catch (GeneralSecurityException e) { Log_OC.e( TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e); } catch (IOException e) { Log_OC.e( TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e); } WebdavClient client = new WebdavClient(getMultiThreadedConnManager()); client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); client.setBaseUri(uri); client.setFollowRedirects(followRedirects); return client; }
public void uploadFiles() { try { WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext()); // create last directory in path if necessary if (mCreateDir) { wdc.createDirectory(mUploadPath); } String[] local = new String[mStreamsToUpload.size()], remote = new String[mStreamsToUpload.size()]; for (int i = 0; i < mStreamsToUpload.size(); ++i) { Uri uri = (Uri) mStreamsToUpload.get(i); if (uri.getScheme().equals("content")) { Cursor c = getContentResolver() .query((Uri) mStreamsToUpload.get(i), CONTENT_PROJECTION, null, null, null); if (!c.moveToFirst()) continue; final String display_name = c.getString(c.getColumnIndex(Media.DISPLAY_NAME)), data = c.getString(c.getColumnIndex(Media.DATA)); local[i] = data; remote[i] = mUploadPath + display_name; } else if (uri.getScheme().equals("file")) { final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme() + "://", "")); local[i] = file.getAbsolutePath(); remote[i] = mUploadPath + file.getName(); } } Intent intent = new Intent(getApplicationContext(), FileUploader.class); intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES); intent.putExtra(FileUploader.KEY_LOCAL_FILE, local); intent.putExtra(FileUploader.KEY_REMOTE_FILE, remote); intent.putExtra(FileUploader.KEY_ACCOUNT, mAccount); startService(intent); finish(); } catch (SecurityException e) { String message = String.format( getString(R.string.uploader_error_forbidden_content), getString(R.string.app_name)); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } }
private boolean tryConnection(WebdavClient wc, String urlSt) { boolean retval = false; GetMethod get = null; try { get = new GetMethod(urlSt); int status = wc.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT); String response = get.getResponseBodyAsString(); if (status == HttpStatus.SC_OK) { JSONObject json = new JSONObject(response); if (!json.getBoolean("installed")) { mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); } else { mOCVersion = new OwnCloudVersion(json.getString("version")); if (!mOCVersion.isVersionValid()) { mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION); } else { mLatestResult = new RemoteOperationResult( urlSt.startsWith("https://") ? RemoteOperationResult.ResultCode.OK_SSL : RemoteOperationResult.ResultCode.OK_NO_SSL); retval = true; } } } else { mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders()); } } catch (JSONException e) { mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); } catch (Exception e) { mLatestResult = new RemoteOperationResult(e); } finally { if (get != null) get.releaseConnection(); } if (mLatestResult.isSuccess()) { Log_OC.i(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage()); } else if (mLatestResult.getException() != null) { Log_OC.e( TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage(), mLatestResult.getException()); } else { Log_OC.e(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage()); } return retval; }
@Override protected RemoteOperationResult run(WebdavClient client) { if (!isOnline()) { return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION); } if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) { tryConnection(client, mUrl + AccountUtils.STATUS_PATH); } else { client.setBaseUri(Uri.parse("https://" + mUrl + AccountUtils.STATUS_PATH)); boolean httpsSuccess = tryConnection(client, "https://" + mUrl + AccountUtils.STATUS_PATH); if (!httpsSuccess && !mLatestResult.isSslRecoverableException()) { Log_OC.d(TAG, "establishing secure connection failed, trying non secure connection"); client.setBaseUri(Uri.parse("http://" + mUrl + AccountUtils.STATUS_PATH)); tryConnection(client, "http://" + mUrl + AccountUtils.STATUS_PATH); } } return mLatestResult; }
@Override protected RemoteOperationResult run(WebdavClient client) { RemoteOperationResult result = null; // code before in FileSyncAdapter.fetchData PropFindMethod query = null; try { Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath); // remote request query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); int status = client.executeMethod(query); // check and process response - /// TODO take into account all the possible status per // child-resource if (isMultiStatus(status)) { MultiStatus resp = query.getResponseBodyAsMultiStatus(); // synchronize properties of the parent folder, if necessary if (mParentId == DataStorageManager.ROOT_PARENT_ID) { WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath()); OCFile parent = fillOCFile(we); parent.setParentId(mParentId); mStorageManager.saveFile(parent); mParentId = parent.getFileId(); } // read contents in folder List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1); for (int i = 1; i < resp.getResponses().length; ++i) { WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath()); OCFile file = fillOCFile(we); file.setParentId(mParentId); OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath()); if (oldFile != null) { if (oldFile.keepInSync() && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) { disableObservance( file); // first disable observer so we won't get file upload right after download requestContentDownload(file); } file.setKeepInSync(oldFile.keepInSync()); } updatedFiles.add(file); } // save updated contents in local database; all at once, trying to get a best performance in // database update (not a big deal, indeed) mStorageManager.saveFiles(updatedFiles); // removal of obsolete files mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId)); OCFile file; String currentSavePath = FileDownloader.getSavePath(mAccount.name); for (int i = 0; i < mChildren.size(); ) { file = mChildren.get(i); if (file.getLastSyncDate() != mCurrentSyncTime) { Log.d(TAG, "removing file: " + file); mStorageManager.removeFile( file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath))); mChildren.remove(i); } else { i++; } } } else { client.exhaustResponse(query.getResponseBodyAsStream()); } // prepare result object result = new RemoteOperationResult(isMultiStatus(status), status); Log.i( TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage()); } catch (Exception e) { result = new RemoteOperationResult(e); Log.e( TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException()); } finally { if (query != null) query.releaseConnection(); // let the connection available for other methods } return result; }
public void run() { AccountManager am = AccountManager.get(getActivity()); Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity()); OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION)); String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv); Log.d("share", "sharing for version " + ocv.toString()); if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) { String APPS_PATH = "/apps/files_sharing/"; String SHARE_PATH = "ajax/share.php"; String SHARED_PATH = "/apps/files_sharing/get.php?token="; final String WEBDAV_SCRIPT = "webdav.php"; final String WEBDAV_FILES_LOCATION = "/files/"; WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient( account, getActivity().getApplicationContext()); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5); // wc.getParams().setParameter("http.protocol.single-cookie-header", true); // wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod post = new PostMethod( am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH); post.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Log.d("share", mPath + ""); formparams.add(new BasicNameValuePair("sources", mPath)); formparams.add(new BasicNameValuePair("uid_shared_with", "public")); formparams.add(new BasicNameValuePair("permissions", "0")); post.setRequestEntity( new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8))); int status; try { PropFindMethod find = new PropFindMethod(url + "/"); find.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); Log.d("sharer", "" + url + "/"); for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) { Log.d("sharer-h", a.getName() + ":" + a.getValue()); } int status2 = wc.executeMethod(find); Log.d("sharer", "propstatus " + status2); GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/"); get.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); status2 = wc.executeMethod(get); Log.d("sharer", "getstatus " + status2); Log.d("sharer", "" + get.getResponseBodyAsString()); for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) { Log.d("sharer", a.getName() + ":" + a.getValue()); } status = wc.executeMethod(post); for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) { Log.d("sharer-h", a.getName() + ":" + a.getValue()); } for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) { Log.d("sharer", a.getName() + ":" + a.getValue()); } String resp = post.getResponseBodyAsString(); Log.d("share", "" + post.getURI().toString()); Log.d("share", "returned status " + status); Log.d("share", " " + resp); if (status != HttpStatus.SC_OK || resp == null || resp.equals("") || resp.startsWith("false")) { return; } JSONObject jsonObject = new JSONObject(resp); String jsonStatus = jsonObject.getString("status"); if (!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success"); String token = jsonObject.getString("data"); String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token; Log.d("Actions:shareFile ok", "url: " + uri); } catch (Exception e) { e.printStackTrace(); } } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) { } }
public void run() { WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient( mAccount, getSherlockActivity().getApplicationContext()); AccountManager am = AccountManager.get(getSherlockActivity()); String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL); OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION)); String webdav_path = AccountUtils.getWebdavPath(ocv); Log.d("ASD", "" + baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath())); Log.e( "ASD", Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath())); LocalMoveMethod move = new LocalMoveMethod( baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()), Uri.parse(baseUrl).getPath() == null ? "" : Uri.parse(baseUrl).getPath() + webdav_path + WebdavUtils.encodePath(mNew.getRemotePath())); boolean success = false; try { int status = wc.executeMethod(move); success = move.succeeded(); move.getResponseBodyAsString(); // exhaust response, although not interesting Log.d(TAG, "Move returned status: " + status); } catch (HttpException e) { Log.e( TAG, "HTTP Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e); } catch (IOException e) { Log.e( TAG, "I/O Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e); } catch (Exception e) { Log.e( TAG, "Unexpected exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(), e); } finally { move.releaseConnection(); } if (success) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); fdsm.removeFile(mOld, false); fdsm.saveFile(mNew); mFile = mNew; mHandler.post( new Runnable() { @Override public void run() { boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .dismissDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); updateFileDetails(mFile, mAccount); mContainerActivity.onFileStateChanged(); } }); } else { mHandler.post( new Runnable() { @Override public void run() { // undo the local rename if (mNew.isDown()) { File f = new File(mNew.getStoragePath()); if (!f.renameTo(new File(mOld.getStoragePath()))) { // the local rename undoing failed; last chance: save the new local storage path // in the old file mFile.setStoragePath(mNew.getStoragePath()); FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); fdsm.saveFile(mFile); } } boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .dismissDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); try { Toast msg = Toast.makeText( getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG); msg.show(); } catch (NotFoundException e) { e.printStackTrace(); } } }); } }
public void run() { WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient( mAccount, getSherlockActivity().getApplicationContext()); AccountManager am = AccountManager.get(getSherlockActivity()); String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL); OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION)); String webdav_path = AccountUtils.getWebdavPath(ocv); Log.d( "ASD", "" + baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath())); DeleteMethod delete = new DeleteMethod( baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath())); boolean success = false; int status = -1; try { status = wc.executeMethod(delete); success = (delete.succeeded()); delete.getResponseBodyAsString(); // exhaust the response, although not interesting Log.d(TAG, "Delete: returned status " + status); } catch (HttpException e) { Log.e(TAG, "HTTP Exception removing file " + mFileToRemove.getRemotePath(), e); } catch (IOException e) { Log.e(TAG, "I/O Exception removing file " + mFileToRemove.getRemotePath(), e); } catch (Exception e) { Log.e(TAG, "Unexpected exception removing file " + mFileToRemove.getRemotePath(), e); } finally { delete.releaseConnection(); } if (success) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); fdsm.removeFile(mFileToRemove, true); mHandler.post( new Runnable() { @Override public void run() { boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .dismissDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); try { Toast msg = Toast.makeText( getActivity().getApplicationContext(), R.string.remove_success_msg, Toast.LENGTH_LONG); msg.show(); if (inDisplayActivity) { // double pane FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction(); transaction.replace( R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment transaction.commit(); mContainerActivity.onFileStateChanged(); } else { getActivity().finish(); } } catch (NotFoundException e) { e.printStackTrace(); } } }); } else { mHandler.post( new Runnable() { @Override public void run() { boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .dismissDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); try { Toast msg = Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG); msg.show(); } catch (NotFoundException e) { e.printStackTrace(); } } }); } }
@Override protected RemoteOperationResult run(WebdavClient client) { AccountManager accountMngr = AccountManager.get(mContext); String statUrl = accountMngr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL); statUrl += AccountUtils.STATUS_PATH; RemoteOperationResult result = null; GetMethod get = null; try { get = new GetMethod(statUrl); int status = client.executeMethod(get); if (status != HttpStatus.SC_OK) { client.exhaustResponse(get.getResponseBodyAsStream()); result = new RemoteOperationResult(false, status); } else { String response = get.getResponseBodyAsString(); if (response != null) { JSONObject json = new JSONObject(response); if (json != null && json.getString("version") != null) { OwnCloudVersion ocver = new OwnCloudVersion(json.getString("version")); if (ocver.isVersionValid()) { accountMngr.setUserData( mAccount, AccountAuthenticator.KEY_OC_VERSION, ocver.toString()); Log.d(TAG, "Got new OC version " + ocver.toString()); result = new RemoteOperationResult(ResultCode.OK); } else { Log.w( TAG, "Invalid version number received from server: " + json.getString("version")); result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION); } } } if (result == null) { result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); } } Log.i( TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage()); } catch (JSONException e) { result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED); Log.e( TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e); } catch (Exception e) { result = new RemoteOperationResult(e); Log.e( TAG, "Check for update of ownCloud server version at " + client.getBaseUri() + ": " + result.getLogMessage(), e); } finally { if (get != null) get.releaseConnection(); } return result; }