Merge pull request #458 from owncloud/operations_service

Operations started by AuthenticatorActivity are run in OperationsService, and end of operations is granted to be dispatched.
This commit is contained in:
masensio 2014-04-08 09:17:47 +02:00
commit 119c61dcf4
17 changed files with 1115 additions and 782 deletions

@ -1 +1 @@
Subproject commit cecda3333ac511267d6a70c61b1475211484ec84
Subproject commit d066e9da51a04837504f9be3e266bdc82caabc64

View file

@ -67,7 +67,7 @@
android:text="@string/auth_check_server"
android:visibility="gone" />
<TextView
android:id="@+id/auth_message"
android:id="@+id/instructions_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"

View file

@ -54,7 +54,7 @@
android:visibility="gone" />
<TextView
android:id="@+id/auth_message"
android:id="@+id/instructions_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_horizontal"

View file

@ -31,7 +31,8 @@
<string name="prefs_imprint">Imprint</string>
<string name="recommend_subject">"Try %1$s on your smartphone!"</string>
<string name="recommend_text">"I want to invite you to use %1$s on your smartphone!\nDownload here: %2$s"</string>
<string name="recommend_text">"I want to invite you to use %1$s on your smartphone!\nDownload here: %2$s"
</string>
<string name="auth_check_server">Check Server</string>
<string name="auth_host_url">Server address https://…</string>
@ -109,6 +110,7 @@
<string name="foreign_files_remote_text">"Remote: %1$s"</string>
<string name="upload_query_move_foreign_files">There is not space enough to copy the selected files into the %1$s folder. Would like to move them into instead? </string>
<string name="pincode_enter_pin_code">Please, insert your App PIN</string>
<string name="pincode_configure_your_pin">Enter your App PIN</string>
<string name="pincode_configure_your_pin_explanation">The PIN will be requested every time the app is started</string>
<string name="pincode_reenter_your_pincode">Please, reenter your App PIN</string>
@ -124,49 +126,51 @@
<string name="media_event_done">"%1$s playback finished"</string>
<string name="media_err_nothing_to_play">No media file found</string>
<string name="media_err_no_account">No account provided</string>
<string name="media_err_not_in_owncloud">File not in a valid account</string>
<string name="media_err_unsupported">Unsupported media codec</string>
<string name="media_err_io">Media file could not be read</string>
<string name="media_err_malformed">Media file not correctly encoded</string>
<string name="media_err_timeout">Timed out while trying to play</string>
<string name="media_err_invalid_progressive_playback">Media file cannot be streamed</string>
<string name="media_err_unknown">Media file cannot be played with the stock media player</string>
<string name="media_err_security_ex">Security error trying to play %1$s</string>
<string name="media_err_not_in_owncloud">File not in a valid account</string>
<string name="media_err_unsupported">Unsupported media codec</string>
<string name="media_err_io">Media file could not be read</string>
<string name="media_err_malformed">Media file not correctly encoded</string>
<string name="media_err_timeout">Timed out while trying to play</string>
<string name="media_err_invalid_progressive_playback">Media file cannot be streamed</string>
<string name="media_err_unknown">Media file cannot be played with the stock media player</string>
<string name="media_err_security_ex">Security error trying to play %1$s</string>
<string name="media_err_io_ex">Input error trying to play %1$s</string>
<string name="media_err_unexpected">Unexpected error trying to play %1$s</string>
<string name="media_rewind_description">Rewind button</string>
<string name="media_play_pause_description">Play or pause button</string>
<string name="media_forward_description">Fast forward button</string>
<string name="auth_trying_to_login">Trying to login&#8230;</string>
<string name="auth_no_net_conn_title">No network connection</string>
<string name="auth_nossl_plain_ok_title">Secure connection unavailable.</string>
<string name="auth_connection_established">Connection established</string>
<string name="auth_testing_connection">Testing connection&#8230;</string>
<string name="auth_not_configured_title">Malformed server configuration</string>
<string name="auth_account_not_new">An account for the same user and server already exists in the device</string>
<string name="auth_account_not_the_same">The entered user does not match the user of this account</string>
<string name="auth_unknown_error_title">Unknown error occurred!</string>
<string name="auth_unknown_host_title">Couldn\'t find host</string>
<string name="auth_incorrect_path_title">Server instance not found</string>
<string name="auth_timeout_title">The server took too long to respond</string>
<string name="auth_incorrect_address_title">Malformed URL</string>
<string name="auth_ssl_general_error_title">SSL initialization failed</string>
<string name="auth_ssl_unverified_server_title">Couldn\'t verify SSL server\'s identity</string>
<string name="auth_bad_oc_version_title">Unrecognized server version</string>
<string name="auth_wrong_connection_title">Couldn\'t establish connection</string>
<string name="auth_secure_connection">Secure connection established</string>
<string name="auth_unauthorized">Wrong username or password</string>
<string name="auth_getting_authorization">Getting authorization&#8230;</string>
<string name="auth_trying_to_login">Trying to login&#8230;</string>
<string name="auth_no_net_conn_title">No network connection</string>
<string name="auth_nossl_plain_ok_title">Secure connection unavailable.</string>
<string name="auth_connection_established">Connection established</string>
<string name="auth_testing_connection">Testing connection&#8230;</string>
<string name="auth_not_configured_title">Malformed server configuration</string>
<string name="auth_account_not_new">An account for the same user and server already exists in the device</string>
<string name="auth_account_not_the_same">The entered user does not match the user of this account</string>
<string name="auth_unknown_error_title">Unknown error occurred!</string>
<string name="auth_unknown_host_title">Couldn\'t find host</string>
<string name="auth_incorrect_path_title">Server instance not found</string>
<string name="auth_timeout_title">The server took too long to respond</string>
<string name="auth_incorrect_address_title">Malformed URL</string>
<string name="auth_ssl_general_error_title">SSL initialization failed</string>
<string name="auth_ssl_unverified_server_title">Couldn\'t verify SSL server\'s identity</string>
<string name="auth_bad_oc_version_title">Unrecognized server version</string>
<string name="auth_wrong_connection_title">Couldn\'t establish connection</string>
<string name="auth_secure_connection">Secure connection established</string>
<string name="auth_unauthorized">Wrong username or password</string>
<string name="auth_oauth_error">Unsuccessful authorization</string>
<string name="auth_oauth_error_access_denied">Access denied by authorization server</string>
<string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
<string name="auth_expired_oauth_token_toast">Your authorization expired. Please, authorize again</string>
<string name="auth_expired_basic_auth_toast">Please, enter the current password</string>
<string name="auth_expired_saml_sso_token_toast">Your session expired. Please connect again</string>
<string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
<string name="auth_expired_oauth_token_toast">Your authorization expired. Please, authorize again</string>
<string name="auth_expired_basic_auth_toast">Please, enter the current password</string>
<string name="auth_expired_saml_sso_token_toast">Your session expired. Please connect again</string>
<string name="auth_connecting_auth_server">Connecting to authentication server…</string>
<string name="auth_unsupported_auth_method">The server does not support this authentication method</string>
<string name="auth_unsupported_auth_method">The server does not support this authentication method</string>
<string name="auth_unsupported_multiaccount">%1$s does not support multiple accounts</string>
<string name="auth_fail_get_user_name">Your server is not returning a correct user id, please contact an administrator</string>
<string name="auth_fail_get_user_name">Your server is not returning a correct user id, please contact an administrator
</string>
<string name="auth_can_not_auth_against_server">Can not authenticate against this server</string>
<string name="fd_keep_in_sync">Keep file up to date</string>
@ -250,8 +254,9 @@
<string name="failed_upload_retry_do_nothing_text">do nothing you are not online for instant upload</string>
<string name="failed_upload_failure_text">Failure Message: </string>
<string name="failed_upload_quota_exceeded_text">Please check your server configuration,maybe your quota is exceeded.</string>
<string name="share_link_no_support_share_api">Sorry, sharing is not enabled on your server. Please contact your administrator.</string>
<string name="share_link_no_support_share_api">Sorry, sharing is not enabled on your server. Please contact your
administrator.</string>
<string name="share_link_file_no_exist">Unable to share this file or folder. Please, make sure it exists</string>
<string name="share_link_file_error">An error occurred while trying to share this file or folder</string>
<string name="unshare_link_file_no_exist">Unable to unshare this file or folder. It does not exist.</string>
@ -259,7 +264,8 @@
<string name="activity_chooser_send_file_title">Send</string>
<string name="copy_link">Copy link</string>
<string name="copy_link">Copy link</string>
<string name="clipboard_text_copied">Copied to clipboard</string>
<string name="error_cant_bind_to_operations_service">Critical error: can not perform operations</string>
</resources>

View file

@ -195,8 +195,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
intent.putExtra(KEY_LOGIN_OPTIONS, options);
intent.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
intent.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
final Bundle bundle = new Bundle();

View file

@ -115,7 +115,7 @@ public class FileOperationsHelper {
service.putExtra(OperationsService.EXTRA_ACCOUNT, callerActivity.getAccount());
service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
service.putExtra(OperationsService.EXTRA_SEND_INTENT, sendIntent);
callerActivity.startService(service);
callerActivity.getOperationsServiceBinder().newOperation(service);
} else {
Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
@ -154,7 +154,7 @@ public class FileOperationsHelper {
service.setAction(OperationsService.ACTION_UNSHARE);
service.putExtra(OperationsService.EXTRA_ACCOUNT, callerActivity.getAccount());
service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
callerActivity.startService(service);
callerActivity.getOperationsServiceBinder().newOperation(service);
callerActivity.showLoadingDialog();

View file

@ -478,8 +478,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);

View file

@ -785,8 +785,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);

View file

@ -64,14 +64,17 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
}
private Context mContext;
private String mWebDavUrl;
/**
* Constructor
*
* @param context Android context of the caller.
* @param webdavUrl
*/
public DetectAuthenticationMethodOperation(Context context) {
public DetectAuthenticationMethodOperation(Context context, String webdavUrl) {
mContext = context;
mWebDavUrl = webdavUrl;
}
@ -90,6 +93,7 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
AuthenticationMethod authMethod = AuthenticationMethod.UNKNOWN;
RemoteOperation operation = new ExistenceCheckRemoteOperation("", mContext, false);
client.setWebdavUri(Uri.parse(mWebDavUrl));
client.setBasicCredentials("", "");
client.setFollowRedirects(false);
@ -122,6 +126,9 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
// else - fall back to UNKNOWN
Log.d(TAG, "Authentication method found: " + authenticationMethodToString(authMethod));
if (!authMethod.equals(AuthenticationMethod.UNKNOWN)) {
result = new RemoteOperationResult(true, result.getHttpCode(), null);
}
ArrayList<Object> data = new ArrayList<Object>();
data.add(authMethod);
result.setData(data);

View file

@ -0,0 +1,164 @@
/* ownCloud Android Library is available under MIT license
* Copyright (C) 2014 ownCloud Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.operations;
import java.util.ArrayList;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
import com.owncloud.android.utils.Log_OC;
import android.content.Context;
/**
* Get basic information from an ownCloud server given its URL.
*
* Checks the existence of a configured ownCloud server in the URL, gets its version
* and finds out what authentication method is needed to access files in it.
*
* @author David A. Velasco
* @author masensio
*/
public class GetServerInfoOperation extends RemoteOperation {
private static final String TAG = GetServerInfoOperation.class.getSimpleName();
private String mUrl;
private String mAuthTokenType;
private Context mContext;
private ServerInfo mResultData;
/**
* Constructor.
*
* @param url URL to an ownCloud server.
* @param authTokenType Identifies the authorization token supported by the caller;
* TODO ugly dependency, get rid of it.
* @param context Android context; needed to check network state
* TODO ugly dependency, get rid of it.
*/
public GetServerInfoOperation(String url, String authTokenType, Context context) {
mUrl = trimWebdavSuffix(url);
mAuthTokenType = authTokenType;
mContext = context;
mResultData = new ServerInfo();
}
/**
* Performs the operation
*
* @return Result of the operation. If successful, includes an instance of
* {@link ServerInfo} with the information retrieved from the server.
* Call {@link RemoteOperationResult#getData()}.get(0) to get it.
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
// first: check the status of the server (including its version)
GetRemoteStatusOperation getStatus = new GetRemoteStatusOperation(mUrl, mContext);
RemoteOperationResult result = getStatus.execute(client);
if (result.isSuccess()) {
// second: get authentication method required by the server
mResultData.mVersion = (OwnCloudVersion)(result.getData().get(0));
mResultData.mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
mResultData.mBaseUrl = normalizeProtocolPrefix(mUrl, mResultData.mIsSslConn);
RemoteOperationResult detectAuthResult = detectAuthorizationMethod(client);
// third: merge results
if (detectAuthResult.isSuccess()) {
mResultData.mAuthMethod =
(AuthenticationMethod)detectAuthResult.getData().get(0);
ArrayList<Object> data = new ArrayList<Object>();
data.add(mResultData);
result.setData(data);
} else {
result = detectAuthResult;
}
}
return result;
}
private RemoteOperationResult detectAuthorizationMethod(OwnCloudClient client) {
Log_OC.d(TAG, "Trying empty authorization to detect authentication method");
String webdav_path = AccountUtils.getWebdavPath(mResultData.mVersion, mAuthTokenType);
String webdav_url = mResultData.mBaseUrl + webdav_path;
DetectAuthenticationMethodOperation operation =
new DetectAuthenticationMethodOperation(mContext, webdav_url);
return operation.execute(client);
}
private String trimWebdavSuffix(String url) {
if (url == null) {
url = "";
} else {
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
} else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
} else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
}
}
return url;
}
private String normalizeProtocolPrefix(String url, boolean isSslConn) {
if (!url.toLowerCase().startsWith("http://") &&
!url.toLowerCase().startsWith("https://")) {
if (isSslConn) {
return "https://" + url;
} else {
return "http://" + url;
}
}
return url;
}
public static class ServerInfo {
public OwnCloudVersion mVersion = null;
public String mBaseUrl = "";
public AuthenticationMethod mAuthMethod = AuthenticationMethod.UNKNOWN;
public boolean mIsSslConn = false;
}
}

View file

@ -1,5 +1,6 @@
package com.owncloud.android.operations;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@ -37,15 +38,12 @@ public class OAuth2GetAccessToken extends RemoteOperation {
mOAuth2ParsedAuthorizationResponse = new HashMap<String, String>();
mResultTokenMap = null;
}
public Map<String, String> getOauth2AutorizationResponse() {
return mOAuth2ParsedAuthorizationResponse;
}
/*
public Map<String, String> getResultTokenMap() {
return mResultTokenMap;
}
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
@ -83,6 +81,9 @@ public class OAuth2GetAccessToken extends RemoteOperation {
} else {
result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
ArrayList<Object> data = new ArrayList<Object>();
data.add(mResultTokenMap);
result.setData(data);
}
} else {

View file

@ -1,5 +1,5 @@
/* ownCloud Android client application
* Copyright (C) 2012-2013 ownCloud Inc.
* Copyright (C) 2012-2014 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
@ -18,20 +18,25 @@
package com.owncloud.android.services;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import com.owncloud.android.R;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.lib.common.OwnCloudClientFactory;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
import com.owncloud.android.operations.common.SyncOperation;
import com.owncloud.android.operations.CreateShareOperation;
import com.owncloud.android.operations.GetServerInfoOperation;
import com.owncloud.android.operations.OAuth2GetAccessToken;
import com.owncloud.android.operations.UnshareLinkOperation;
import com.owncloud.android.utils.Log_OC;
@ -47,7 +52,6 @@ import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
//import android.support.v4.content.LocalBroadcastManager;
import android.util.Pair;
public class OperationsService extends Service {
@ -56,24 +60,63 @@ public class OperationsService extends Service {
public static final String EXTRA_ACCOUNT = "ACCOUNT";
public static final String EXTRA_SERVER_URL = "SERVER_URL";
public static final String EXTRA_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
public static final String EXTRA_OAUTH2_QUERY_PARAMETERS = "OAUTH2_QUERY_PARAMETERS";
public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
public static final String EXTRA_SEND_INTENT = "SEND_INTENT";
public static final String EXTRA_RESULT = "RESULT";
// TODO review if ALL OF THEM are necessary
public static final String EXTRA_WEBDAV_PATH = "WEBDAV_PATH";
public static final String EXTRA_SUCCESS_IF_ABSENT = "SUCCESS_IF_ABSENT";
public static final String EXTRA_USERNAME = "USERNAME";
public static final String EXTRA_PASSWORD = "PASSWORD";
public static final String EXTRA_AUTH_TOKEN = "AUTH_TOKEN";
public static final String EXTRA_FOLLOW_REDIRECTS = "FOLLOW_REDIRECTS";
public static final String EXTRA_COOKIE = "COOKIE";
public static final String ACTION_CREATE_SHARE = "CREATE_SHARE";
public static final String ACTION_UNSHARE = "UNSHARE";
public static final String ACTION_GET_SERVER_INFO = "GET_SERVER_INFO";
public static final String ACTION_OAUTH2_GET_ACCESS_TOKEN = "OAUTH2_GET_ACCESS_TOKEN";
public static final String ACTION_EXISTENCE_CHECK = "EXISTENCE_CHECK";
public static final String ACTION_GET_USER_NAME = "GET_USER_NAME";
public static final String ACTION_OPERATION_ADDED = OperationsService.class.getName() + ".OPERATION_ADDED";
public static final String ACTION_OPERATION_FINISHED = OperationsService.class.getName() + ".OPERATION_FINISHED";
private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations = new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
private ConcurrentLinkedQueue<Pair<Target, RemoteOperation>> mPendingOperations =
new ConcurrentLinkedQueue<Pair<Target, RemoteOperation>>();
/*
private ConcurrentMap<Integer, RemoteOperationResult> mOperationResults =
new ConcurrentHashMap<Integer, RemoteOperationResult>();
*/
private ConcurrentMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>
mUndispatchedFinishedOperations =
new ConcurrentHashMap<Integer, Pair<RemoteOperation, RemoteOperationResult>>();
private static class Target {
public Uri mServerUrl = null;
public Account mAccount = null;
public Target(Account account, Uri serverUrl) {
public String mWebDavUrl = null;
public String mUsername = null;
public String mPassword = null;
public String mAuthToken = null;
public boolean mFollowRedirects = true;
public String mCookie = null;
public Target(Account account, Uri serverUrl, String webdavUrl, String username, String password, String authToken,
boolean followRedirects, String cookie) {
mAccount = account;
mServerUrl = serverUrl;
mWebDavUrl = webdavUrl;
mUsername = username;
mPassword = password;
mAuthToken = authToken;
mFollowRedirects = followRedirects;
mCookie = cookie;
}
}
@ -99,6 +142,7 @@ public class OperationsService extends Service {
mBinder = new OperationsServiceBinder();
}
/**
* Entry point to add a new operation to the queue of operations.
*
@ -110,57 +154,31 @@ public class OperationsService extends Service {
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!intent.hasExtra(EXTRA_ACCOUNT) && !intent.hasExtra(EXTRA_SERVER_URL)) {
Log_OC.e(TAG, "Not enough information provided in intent");
return START_NOT_STICKY;
}
try {
Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
String serverUrl = intent.getStringExtra(EXTRA_SERVER_URL);
Target target = new Target(account, (serverUrl == null) ? null : Uri.parse(serverUrl));
RemoteOperation operation = null;
String action = intent.getAction();
if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
Intent sendIntent = intent.getParcelableExtra(EXTRA_SEND_INTENT);
if (remotePath.length() > 0) {
operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
"", false, "", 1, sendIntent);
}
} else if (action.equals(ACTION_UNSHARE)) { // Unshare file
String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
if (remotePath.length() > 0) {
operation = new UnshareLinkOperation(remotePath, this.getApplicationContext());
}
} else {
// nothing we are going to handle
return START_NOT_STICKY;
}
mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
//sendBroadcastNewOperation(target, operation);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
} catch (IllegalArgumentException e) {
Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
return START_NOT_STICKY;
}
//Log_OC.wtf(TAG, "onStartCommand init" );
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
//Log_OC.wtf(TAG, "onStartCommand end" );
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
//Log_OC.wtf(TAG, "onDestroy init" );
super.onDestroy();
//Log_OC.wtf(TAG, "Clear mUndispatchedFinisiedOperations" );
mUndispatchedFinishedOperations.clear();
//Log_OC.wtf(TAG, "onDestroy end" );
}
/**
* Provides a binder object that clients can use to perform actions on the queue of operations,
* except the addition of new operations.
*/
@Override
public IBinder onBind(Intent intent) {
//Log_OC.wtf(TAG, "onBind" );
return mBinder;
}
@ -170,7 +188,7 @@ public class OperationsService extends Service {
*/
@Override
public boolean onUnbind(Intent intent) {
//((OperationsServiceBinder)mBinder).clearListeners();
((OperationsServiceBinder)mBinder).clearListeners();
return false; // not accepting rebinding (default behaviour)
}
@ -185,7 +203,8 @@ public class OperationsService extends Service {
/**
* Map of listeners that will be reported about the end of operations from a {@link OperationsServiceBinder} instance
*/
private Map<OnRemoteOperationListener, Handler> mBoundListeners = new HashMap<OnRemoteOperationListener, Handler>();
private ConcurrentMap<OnRemoteOperationListener, Handler> mBoundListeners =
new ConcurrentHashMap<OnRemoteOperationListener, Handler>();
/**
* Cancels an operation
@ -210,7 +229,9 @@ public class OperationsService extends Service {
* @param callbackHandler {@link Handler} to access the listener without breaking Android threading protection.
*/
public void addOperationListener (OnRemoteOperationListener listener, Handler callbackHandler) {
mBoundListeners.put(listener, callbackHandler);
synchronized (mBoundListeners) {
mBoundListeners.put(listener, callbackHandler);
}
}
@ -220,7 +241,9 @@ public class OperationsService extends Service {
* @param listener Object to notify about progress of transfer.
*/
public void removeOperationListener (OnRemoteOperationListener listener) {
mBoundListeners.remove(listener);
synchronized (mBoundListeners) {
mBoundListeners.remove(listener);
}
}
@ -233,6 +256,117 @@ public class OperationsService extends Service {
return (!mPendingOperations.isEmpty());
}
/**
* Creates and adds to the queue a new operation, as described by operationIntent
*
* @param operationIntent Intent describing a new operation to queue and execute.
* @return Identifier of the operation created, or null if failed.
*/
public long newOperation(Intent operationIntent) {
RemoteOperation operation = null;
Target target = null;
try {
if (!operationIntent.hasExtra(EXTRA_ACCOUNT) &&
!operationIntent.hasExtra(EXTRA_SERVER_URL)) {
Log_OC.e(TAG, "Not enough information provided in intent");
} else {
Account account = operationIntent.getParcelableExtra(EXTRA_ACCOUNT);
String serverUrl = operationIntent.getStringExtra(EXTRA_SERVER_URL);
String webDavPath = operationIntent.getStringExtra(EXTRA_WEBDAV_PATH);
String webDavUrl = serverUrl + webDavPath;
String username = operationIntent.getStringExtra(EXTRA_USERNAME);
String password = operationIntent.getStringExtra(EXTRA_PASSWORD);
String authToken = operationIntent.getStringExtra(EXTRA_AUTH_TOKEN);
boolean followRedirects = operationIntent.getBooleanExtra(EXTRA_FOLLOW_REDIRECTS, true);
String cookie = operationIntent.getStringExtra(EXTRA_COOKIE);
target = new Target(
account,
(serverUrl == null) ? null : Uri.parse(serverUrl),
((webDavPath == null) || (serverUrl == null)) ? null : webDavUrl,
username,
password,
authToken,
followRedirects,
cookie
);
String action = operationIntent.getAction();
if (action.equals(ACTION_CREATE_SHARE)) { // Create Share
String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
Intent sendIntent = operationIntent.getParcelableExtra(EXTRA_SEND_INTENT);
if (remotePath.length() > 0) {
operation = new CreateShareOperation(remotePath, ShareType.PUBLIC_LINK,
"", false, "", 1, sendIntent);
}
} else if (action.equals(ACTION_UNSHARE)) { // Unshare file
String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
if (remotePath.length() > 0) {
operation = new UnshareLinkOperation(
remotePath,
OperationsService.this);
}
} else if (action.equals(ACTION_GET_SERVER_INFO)) {
// check OC server and get basic information from it
String authTokenType =
operationIntent.getStringExtra(EXTRA_AUTH_TOKEN_TYPE);
operation = new GetServerInfoOperation(
serverUrl, authTokenType, OperationsService.this);
} else if (action.equals(ACTION_OAUTH2_GET_ACCESS_TOKEN)) {
/// GET ACCESS TOKEN to the OAuth server
String oauth2QueryParameters =
operationIntent.getStringExtra(EXTRA_OAUTH2_QUERY_PARAMETERS);
operation = new OAuth2GetAccessToken(
getString(R.string.oauth2_client_id),
getString(R.string.oauth2_redirect_uri),
getString(R.string.oauth2_grant_type),
oauth2QueryParameters);
} else if (action.equals(ACTION_EXISTENCE_CHECK)) {
// Existence Check
String remotePath = operationIntent.getStringExtra(EXTRA_REMOTE_PATH);
boolean successIfAbsent = operationIntent.getBooleanExtra(EXTRA_SUCCESS_IF_ABSENT, true);
operation = new ExistenceCheckRemoteOperation(remotePath, OperationsService.this, successIfAbsent);
} else if (action.equals(ACTION_GET_USER_NAME)) {
// Get User Name
operation = new GetRemoteUserNameOperation();
}
}
} catch (IllegalArgumentException e) {
Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
operation = null;
}
if (operation != null) {
mPendingOperations.add(new Pair<Target , RemoteOperation>(target, operation));
startService(new Intent(OperationsService.this, OperationsService.class));
//Log_OC.wtf(TAG, "New operation added, opId: " + operation.hashCode());
// better id than hash? ; should be good enough by the time being
return operation.hashCode();
} else {
//Log_OC.wtf(TAG, "New operation failed, returned Long.MAX_VALUE");
return Long.MAX_VALUE;
}
}
public void dispatchResultIfFinished(int operationId, OnRemoteOperationListener listener) {
Pair<RemoteOperation, RemoteOperationResult> undispatched =
mUndispatchedFinishedOperations.remove(operationId);
if (undispatched != null) {
listener.onRemoteOperationFinish(undispatched.first, undispatched.second);
//Log_OC.wtf(TAG, "Sending callback later");
} else {
//Log_OC.wtf(TAG, "Not finished yet");
}
}
}
@ -265,11 +399,13 @@ public class OperationsService extends Service {
*/
private void nextOperation() {
//Log_OC.wtf(TAG, "nextOperation init" );
Pair<Target, RemoteOperation> next = null;
synchronized(mPendingOperations) {
next = mPendingOperations.peek();
}
if (next != null) {
mCurrentOperation = next.second;
@ -282,7 +418,18 @@ public class OperationsService extends Service {
mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mAccount, getApplicationContext());
mStorageManager = new FileDataStorageManager(mLastTarget.mAccount, getContentResolver());
} else {
mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(), true); // this is not good enough
mOwnCloudClient = OwnCloudClientFactory.createOwnCloudClient(mLastTarget.mServerUrl, getApplicationContext(),
mLastTarget.mFollowRedirects); // this is not good enough
if (mLastTarget.mWebDavUrl != null) {
mOwnCloudClient.setWebdavUri(Uri.parse(mLastTarget.mWebDavUrl));
}
if (mLastTarget.mUsername != null && mLastTarget.mPassword != null) {
mOwnCloudClient.setBasicCredentials(mLastTarget.mUsername, mLastTarget.mPassword);
} else if (mLastTarget.mAuthToken != null) {
mOwnCloudClient.setBearerCredentials(mLastTarget.mAuthToken);
} else if (mLastTarget.mCookie != null) {
mOwnCloudClient.setSsoSessionCookie(mLastTarget.mCookie);
}
mStorageManager = null;
}
}
@ -324,7 +471,7 @@ public class OperationsService extends Service {
}
//sendBroadcastOperationFinished(mLastTarget, mCurrentOperation, result);
callbackOperationListeners(mLastTarget, mCurrentOperation, result);
dispatchResultToOperationListeners(mLastTarget, mCurrentOperation, result);
}
}
@ -382,7 +529,9 @@ public class OperationsService extends Service {
* @param operation Finished operation.
* @param result Result of the operation.
*/
private void callbackOperationListeners(Target target, final RemoteOperation operation, final RemoteOperationResult result) {
private void dispatchResultToOperationListeners(
Target target, final RemoteOperation operation, final RemoteOperationResult result) {
int count = 0;
Iterator<OnRemoteOperationListener> listeners = mBinder.mBoundListeners.keySet().iterator();
while (listeners.hasNext()) {
final OnRemoteOperationListener listener = listeners.next();
@ -394,9 +543,16 @@ public class OperationsService extends Service {
listener.onRemoteOperationFinish(operation, result);
}
});
count += 1;
}
}
if (count == 0) {
//mOperationResults.put(operation.hashCode(), result);
Pair<RemoteOperation, RemoteOperationResult> undispatched =
new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
mUndispatchedFinishedOperations.put(operation.hashCode(), undispatched);
}
Log_OC.d(TAG, "Called " + count + " listeners");
}

View file

@ -397,8 +397,7 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
// let the user update credentials with one click
Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);

View file

@ -151,6 +151,7 @@ public class FileActivity extends SherlockFragmentActivity implements OnRemoteOp
@Override
protected void onStart() {
super.onStart();
if (mAccountWasSet) {
onAccountSet(mAccountWasRestored);
}
@ -162,10 +163,12 @@ public class FileActivity extends SherlockFragmentActivity implements OnRemoteOp
@Override
protected void onStop() {
super.onStop();
if (mOperationsServiceBinder != null) {
mOperationsServiceBinder.removeOperationListener(this);
}
super.onStop();
}
@ -302,6 +305,11 @@ public class FileActivity extends SherlockFragmentActivity implements OnRemoteOp
}
public OperationsServiceBinder getOperationsServiceBinder() {
return mOperationsServiceBinder;
}
/**
* Helper class handling a callback from the {@link AccountManager} after the creation of
* a new ownCloud {@link Account} finished, successfully or not.

View file

@ -19,6 +19,7 @@
package com.owncloud.android.ui.activity;
import java.io.File;
import android.accounts.Account;
import android.app.AlertDialog;
import android.app.Dialog;

View file

@ -72,7 +72,7 @@ public class SamlWebViewDialog extends SherlockDialogFragment {
*
* @param handler
* @param Url Url to open at WebView
* @param targetURL mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType)
* @param targetURL mBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType)
* @return New dialog instance, ready to show.
*/
public static SamlWebViewDialog newInstance(String url, String targetUrl) {