Эх сурвалжийг харах

Cleaning-up AuthenticatorActivty code

David A. Velasco 12 жил өмнө
parent
commit
088b1e83a4

+ 33 - 16
res/layout-land/account_setup.xml

@@ -58,7 +58,7 @@
                     android:layout_weight="1" >
 
                     <EditText
-                        android:id="@+id/host_URL"
+                        android:id="@+id/hostUrlInput"
                         android:layout_width="match_parent"
                         android:layout_height="wrap_content"
                         android:layout_weight="1"
@@ -74,6 +74,7 @@
                         android:layout_height="wrap_content"
                         android:layout_gravity="right|center_vertical"
                         android:src="@drawable/ic_action_refresh_black"
+                    	android:onClick="onRefreshClick"
                         android:visibility="invisible" />
                 </FrameLayout>
 
@@ -104,7 +105,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:checked="false"
-                    android:onClick="onOff_check_Click"
+                    android:onClick="onCheckClick"
                     android:text="@string/oauth_check_onoff"
                     android:textAppearance="?android:attr/textAppearanceSmall" />
 
@@ -116,19 +117,34 @@
                     android:text="@string/auth_login_details"
                     android:textAppearance="?android:attr/textAppearanceSmall" />
 
-                <EditText
-                    android:id="@+id/oAuth_URL"
-                    android:layout_width="match_parent"
-                    android:layout_height="wrap_content"
-                    android:layout_weight="1"
-                    android:ems="10"
-                    android:hint="@string/oauth_host_url"
-                    android:singleLine="true"
-                    android:visibility="gone" >
-
-                    <requestFocus />
-                </EditText>
-                
+	            <EditText
+	                android:id="@+id/oAuthEntryPoint_1"
+	                android:layout_width="match_parent"
+	                android:layout_height="wrap_content"
+	                android:layout_weight="1"
+	                android:ems="10"
+                	android:enabled="false"
+	                android:text="@string/oauth_url_endpoint_auth"
+	                android:singleLine="true"
+	                android:visibility="gone" >
+	
+	                <requestFocus />
+	            </EditText>            
+	
+	            <EditText
+	                android:id="@+id/oAuthEntryPoint_2"
+	                android:layout_width="match_parent"
+	                android:layout_height="wrap_content"
+	                android:layout_weight="1"
+	                android:ems="10"
+                	android:enabled="false"
+	                android:text="@string/oauth_url_endpoint_access"
+	                android:singleLine="true"
+	                android:visibility="gone" >
+	
+	                <requestFocus />
+	            </EditText>            
+	
                 <LinearLayout
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
@@ -175,11 +191,12 @@
                         android:inputType="textPassword"/>
 
                     <ImageView
-                        android:id="@+id/viewPassword"
+                        android:id="@+id/viewPasswordButton"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:layout_gravity="right|center_vertical"
                         android:src="@android:drawable/ic_menu_view"
+						android:onClick="onViewPasswordClick"
                         android:visibility="invisible" />
                 </FrameLayout>
             </LinearLayout>

+ 22 - 5
res/layout/account_setup.xml

@@ -53,7 +53,7 @@
                 android:layout_weight="1" >
 
                 <EditText
-                    android:id="@+id/host_URL"
+                    android:id="@+id/hostUrlInput"
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"
@@ -68,6 +68,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:src="@drawable/ic_action_refresh_black"
+                    android:onClick="onRefreshClick"
                     android:layout_gravity="right|center_vertical"
                     android:visibility="invisible" />
 
@@ -100,7 +101,7 @@
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:checked="false"
-                android:onClick="onOff_check_Click"
+                android:onClick="onCheckClick"
                 android:text="@string/oauth_check_onoff"
                 android:textAppearance="?android:attr/textAppearanceSmall" />
 
@@ -113,12 +114,27 @@
                 android:textAppearance="?android:attr/textAppearanceSmall" />
             
             <EditText
-                android:id="@+id/oAuth_URL"
+                android:id="@+id/oAuthEntryPoint_1"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:ems="10"
-                android:hint="@string/oauth_host_url"
+                android:enabled="false"
+                android:text="@string/oauth_url_endpoint_auth"
+                android:singleLine="true"
+                android:visibility="gone" >
+
+                <requestFocus />
+            </EditText>            
+
+            <EditText
+                android:id="@+id/oAuthEntryPoint_2"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_weight="1"
+                android:ems="10"
+                android:enabled="false"
+	            android:text="@string/oauth_url_endpoint_access"
                 android:singleLine="true"
                 android:visibility="gone" >
 
@@ -170,11 +186,12 @@
                     android:inputType="textPassword"/>
 
                 <ImageView
-                    android:id="@+id/viewPassword"
+                    android:id="@+id/viewPasswordButton"
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_gravity="right|center_vertical"
                     android:src="@android:drawable/ic_menu_view"
+					android:onClick="onViewPasswordClick"
                     android:visibility="invisible" />
 
             </FrameLayout>

+ 5 - 0
res/values/oauth.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="oauth_url_endpoint_auth">https://frko.surfnetlabs.nl/workshop/php-oauth/authorize.php</string>
+    <string name="oauth_url_endpoint_access">https://frko.surfnetlabs.nl/workshop/php-oauth/token.php</string>
+</resources>

+ 1 - 0
res/values/strings.xml

@@ -179,6 +179,7 @@
     <string name="auth_unauthorized">Invalid login / password</string>
     <string name="auth_not_found">Wrong path given</string>
     <string name="auth_internal">Internal server error, code %1$d</string>
+    <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>

+ 3 - 3
src/com/owncloud/android/AccountUtils.java

@@ -97,10 +97,10 @@ public class AccountUtils {
      * @return webdav path for given OC version, null if OC version unknown
      */
     public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth) {
-        if (supportsOAuth) {
-            return ODAV_PATH;
-        }
         if (version != null) {
+            if (supportsOAuth) {
+                return ODAV_PATH;
+            }
             if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)
                 return WEBDAV_PATH_4_0;
             if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0

+ 2 - 2
src/com/owncloud/android/Uploader.java

@@ -138,8 +138,8 @@ public class Uploader extends ListActivity implements OnItemClickListener, andro
                         // in API7 < this constatant is defined in
                         // Settings.ADD_ACCOUNT_SETTINGS
                         // and Settings.EXTRA_AUTHORITIES
-                        Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
-                        intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+                        Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
+                        intent.putExtra("authorities", new String[] { AccountAuthenticator.AUTHORITY });
                         startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
                     } else {
                         // since in API7 there is no direct call for

+ 27 - 27
src/com/owncloud/android/authenticator/AccountAuthenticator.java

@@ -32,6 +32,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
      * used by application and all extensions.
      */
     public static final String ACCOUNT_TYPE = "owncloud";
+    public static final String AUTHORITY = "org.owncloud";
     public static final String AUTH_TOKEN_TYPE = "org.owncloud";
     public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
     public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
@@ -93,13 +94,13 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
             return e.getFailureBundle();
         }
         final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
-                response);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
         intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
         intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);
         intent.putExtra(KEY_LOGIN_OPTIONS, options);
 
         setIntentFlags(intent);
+        
         final Bundle bundle = new Bundle();
         bundle.putParcelable(AccountManager.KEY_INTENT, intent);
         return bundle;
@@ -138,10 +139,14 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
         return null;
     }
 
+    /**
+     * {@inheritDoc}
+     */
     @Override
     public Bundle getAuthToken(AccountAuthenticatorResponse response,
             Account account, String authTokenType, Bundle options)
             throws NetworkErrorException {
+        /// validate parameters
         try {
             validateAccountType(account.type);
             validateAuthTokenType(authTokenType);
@@ -151,34 +156,29 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
             e.printStackTrace();
             return e.getFailureBundle();
         }
+        
+        /// check if required token is stored
         final AccountManager am = AccountManager.get(mContext);
-        if (authTokenType.equals(AUTH_TOKEN_TYPE_ACCESS_TOKEN)) {
-            final String accessToken = am.peekAuthToken(account, authTokenType);
-            if (accessToken != null) {
-                final Bundle result = new Bundle();
-                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
-                result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
-                result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
-                return result;
-            }
-            
-        } else if (authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD)) {
-            final String password = am.getPassword(account);
-            if (password != null) {
-                final Bundle result = new Bundle();
-                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
-                result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
-                result.putString(AccountManager.KEY_AUTHTOKEN, password);
-                return result;
-            }
+        String accessToken;
+        if (authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD)) {
+            accessToken = am.getPassword(account);
+        } else {
+            accessToken = am.peekAuthToken(account, authTokenType);
         }
-
+        if (accessToken != null) {
+            final Bundle result = new Bundle();
+            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
+            result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
+            result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
+            return result;
+        }
+        
+        /// if not stored, return Intent to access the AuthenticatorActivity
         final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
-        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
-                response);
+        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
         intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
         intent.putExtra(KEY_LOGIN_OPTIONS, options);
-        intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);    // TODO fix, this will pass the accountName, not the username
+        intent.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
 
         final Bundle bundle = new Bundle();
         bundle.putParcelable(AccountManager.KEY_INTENT, intent);
@@ -224,8 +224,8 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
 
     private void setIntentFlags(Intent intent) {
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-        //intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
-        //intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // incompatible with the authorization code grant in OAuth
+        intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // incompatible with the authorization code grant in OAuth
         intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
         intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
     }

+ 0 - 88
src/com/owncloud/android/authenticator/AuthenticationRunnable.java

@@ -1,88 +0,0 @@
-/* ownCloud Android client application
- *   Copyright (C) 2012 Bartek Przybylski
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 3 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.authenticator;
-
-import java.net.URL;
-
-import org.apache.commons.httpclient.HttpStatus;
-
-import com.owncloud.android.R;
-import com.owncloud.android.network.OwnCloudClientUtils;
-
-import eu.alefzero.webdav.WebdavClient;
-
-import android.content.Context;
-import android.net.Uri;
-import android.os.Handler;
-
-public class AuthenticationRunnable implements Runnable {
-
-    private OnAuthenticationResultListener mListener;
-    private Handler mHandler;
-    private URL mUrl;
-    private String mUsername;
-    private String mPassword;
-    private Context mContext;
-
-    public AuthenticationRunnable(URL url, String username, String password, Context context) {
-        mListener = null;
-        mUrl = url;
-        mUsername = username;
-        mPassword = password;
-        mContext = context;
-    }
-
-    public void setOnAuthenticationResultListener(
-            OnAuthenticationResultListener listener, Handler handler) {
-        mListener = listener;
-        mHandler = handler;
-    }
-
-    @Override
-    public void run() {
-        Uri uri;
-        uri = Uri.parse(mUrl.toString());
-        WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(uri, mUsername, mPassword, mContext);
-        int login_result = wdc.tryToLogin();
-        switch (login_result) {
-        case HttpStatus.SC_OK:
-            postResult(true, uri.toString());
-            break;
-        case HttpStatus.SC_UNAUTHORIZED:
-            postResult(false, mContext.getString(R.string.auth_unauthorized));
-            break;
-        case HttpStatus.SC_NOT_FOUND:
-            postResult(false, mContext.getString(R.string.auth_not_found));
-            break;
-        default:
-            postResult(false, String.format(mContext.getString(R.string.auth_internal), login_result));
-        }
-    }
-
-    private void postResult(final boolean success, final String message) {
-        if (mHandler != null && mListener != null) {
-            mHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    mListener.onAuthenticationResult(success, message);
-                }
-            });
-        }
-    }
-}

+ 0 - 25
src/com/owncloud/android/authenticator/OnAuthenticationResultListener.java

@@ -1,25 +0,0 @@
-/* ownCloud Android client application
- *   Copyright (C) 2012 Bartek Przybylski
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 3 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.authenticator;
-
-public interface OnAuthenticationResultListener {
-
-    public void onAuthenticationResult(boolean success, String message);
-
-}

+ 0 - 29
src/com/owncloud/android/authenticator/OnConnectCheckListener.java

@@ -1,29 +0,0 @@
-/* ownCloud Android client application
- *   Copyright (C) 2012 Bartek Przybylski
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 3 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.authenticator;
-
-public interface OnConnectCheckListener {
-
-    enum ResultType {
-        OK_SSL, OK_NO_SSL, SSL_INIT_ERROR, HOST_NOT_AVAILABLE, TIMEOUT, NO_NETWORK_CONNECTION, INCORRECT_ADDRESS, INSTANCE_NOT_CONFIGURED, FILE_NOT_FOUND, UNKNOWN_ERROR, WRONG_CONNECTION,  SSL_UNVERIFIED_SERVER, BAD_OC_VERSION
-    }
-
-    public void onConnectionCheckResult(ResultType type);
-
-}

+ 13 - 2
src/com/owncloud/android/authenticator/oauth2/OAuth2Context.java

@@ -18,8 +18,8 @@ public class OAuth2Context {
     public static final String OAUTH2_G_DEVICE_GETTOKEN_URL = "https://accounts.google.com/o/oauth2/token";
     public static final String OAUTH2_G_DEVICE_GETCODE_SCOPES = "https://www.googleapis.com/auth/userinfo.email";
     
-    public static final String OAUTH2_F_AUTHORIZATION_ENDPOINT_URL = "https://frko.surfnetlabs.nl/workshop/php-oauth/authorize.php";
-    public static final String OAUTH2_F_TOKEN_ENDPOINT_URL = "https://frko.surfnetlabs.nl/workshop/php-oauth/token.php";
+    //public static final String OAUTH2_F_AUTHORIZATION_ENDPOINT_URL = "https://frko.surfnetlabs.nl/workshop/php-oauth/authorize.php";
+    //public static final String OAUTH2_F_TOKEN_ENDPOINT_URL = "https://frko.surfnetlabs.nl/workshop/php-oauth/token.php";
     public static final String OAUTH2_F_CLIENT_ID = "oc-android-test";
     public static final String OAUTH2_F_SCOPE = "grades";
     
@@ -42,4 +42,15 @@ public class OAuth2Context {
     public static final String KEY_GRANT_TYPE = "grant_type";
     public static final String KEY_CODE = "code";
     public static final String KEY_CLIENT_ID = "client_id";
+    
+    public static final String CODE_USER_CODE  =  "user_code";
+    public static final String CODE_CLIENT_ID  =  "client_id";
+    public static final String CODE_SCOPE  =  "scope";    
+    public static final String CODE_VERIFICATION_URL  =  "verification_url";
+    public static final String CODE_EXPIRES_IN  =  "expires_in";
+    public static final String CODE_DEVICE_CODE = "device_code";
+    public static final String CODE_INTERVAL = "interval";
+    public static final String CODE_RESPONSE_TYPE = "response_type";
+    public static final String CODE_REDIRECT_URI = "redirect_uri";
+    
 }

+ 0 - 147
src/com/owncloud/android/authenticator/oauth2/OAuth2GetCodeRunnable.java

@@ -1,147 +0,0 @@
-package com.owncloud.android.authenticator.oauth2;
-
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.http.NameValuePair;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.message.BasicNameValuePair;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.content.Context;
-import android.content.Intent;
-import android.net.ConnectivityManager;
-import android.net.Uri;
-import android.os.Handler;
-import android.util.Log;
-
-import com.owncloud.android.authenticator.oauth2.OnOAuth2GetCodeResultListener.ResultOAuthType;
-import com.owncloud.android.authenticator.oauth2.connection.ConnectorOAuth2;
-
-/**
- * Implements the communication with oAuth2 server to get User Code and other useful values.
- * 
- * @author SolidGear S.L.
- *
- */
-public class OAuth2GetCodeRunnable implements Runnable {
-
-    public static final String CODE_USER_CODE  =  "user_code";
-    public static final String CODE_CLIENT_ID  =  "client_id";
-    public static final String CODE_SCOPE  =  "scope";    
-    public static final String CODE_VERIFICATION_URL  =  "verification_url";
-    public static final String CODE_EXPIRES_IN  =  "expires_in";
-    public static final String CODE_DEVICE_CODE = "device_code";
-    public static final String CODE_INTERVAL = "interval";
-
-    private static final String CODE_RESPONSE_TYPE = "response_type";
-    private static final String CODE_REDIRECT_URI = "redirect_uri";
-    
-    private String mGrantType = OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE;
-    
-    private static final String TAG = "OAuth2GetCodeRunnable";
-    private OnOAuth2GetCodeResultListener mListener;
-    private String mUrl;
-    private Handler mHandler;
-    private Context mContext;
-    private JSONObject codeResponseJson = null;
-    ResultOAuthType mLatestResult;
-
-
-    public void setListener(OnOAuth2GetCodeResultListener listener, Handler handler) {
-        mListener = listener;
-        mHandler = handler;
-    }
-
-    public OAuth2GetCodeRunnable(String url, Context context) {
-        mListener = null;
-        mHandler = null;
-        mUrl = url;
-        mContext = context;
-    }
-
-    @Override
-    public void run() {
-
-        if (!isOnline()) {
-            postResult(ResultOAuthType.NO_NETWORK_CONNECTION,null);
-            return;
-        }
-
-        if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) {        
-            mLatestResult = (mUrl.startsWith("https://"))? ResultOAuthType.OK_SSL : ResultOAuthType.OK_NO_SSL;            
-        } else {
-            mUrl = "https://" + mUrl;
-            mLatestResult = ResultOAuthType.OK_SSL;
-        }
-
-        if (mGrantType.equals(OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE)) {
-            requestBrowserToGetAuthorizationCode();
-            
-        } else if (mGrantType.equals(OAuth2Context.OAUTH_G_DEVICE_GETTOKEN_GRANT_TYPE)) {
-            getAuthorizationCode();
-        }
-    }
-
-    /// open the authorization endpoint in a web browser!
-    private void requestBrowserToGetAuthorizationCode() {
-        Uri uri = Uri.parse(mUrl);
-        Uri.Builder uriBuilder = uri.buildUpon();
-        uriBuilder.appendQueryParameter(CODE_RESPONSE_TYPE, OAuth2Context.OAUTH2_CODE_RESPONSE_TYPE);
-        uriBuilder.appendQueryParameter(CODE_REDIRECT_URI, OAuth2Context.MY_REDIRECT_URI);   
-        uriBuilder.appendQueryParameter(CODE_CLIENT_ID, OAuth2Context.OAUTH2_F_CLIENT_ID);
-        uriBuilder.appendQueryParameter(CODE_SCOPE, OAuth2Context.OAUTH2_F_SCOPE);
-        //uriBuilder.appendQueryParameter(CODE_STATE, whateverwewant);
-        
-        uri = uriBuilder.build();
-        Log.d(TAG, "Starting browser to view " + uri.toString());
-        
-        Intent i = new Intent(Intent.ACTION_VIEW, uri);
-        mContext.startActivity(i);
-        
-        postResult(mLatestResult, null);
-    }
-
-    
-    private void getAuthorizationCode() {
-        ConnectorOAuth2 connectorOAuth2 = new ConnectorOAuth2(mUrl);
-        try {
-            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
-            nameValuePairs.add(new BasicNameValuePair(CODE_CLIENT_ID, OAuth2Context.OAUTH2_G_DEVICE_CLIENT_ID));
-            nameValuePairs.add(new BasicNameValuePair(CODE_SCOPE,OAuth2Context.OAUTH2_G_DEVICE_GETCODE_SCOPES));
-            UrlEncodedFormEntity params = new UrlEncodedFormEntity(nameValuePairs);        
-            codeResponseJson = new JSONObject(connectorOAuth2.connPost(params));         
-        } catch (JSONException e) {
-            Log.e(TAG, "JSONException converting to Json: " + e.toString());
-        } catch (UnsupportedEncodingException e) {
-            Log.e(TAG, "UnsupportedEncodingException encoding URL values: " + e.toString());
-        } catch (Exception e) {
-            Log.e(TAG, "Exception : " + e.toString());
-        }
-
-        if (codeResponseJson == null) {            
-            mLatestResult = ResultOAuthType.HOST_NOT_AVAILABLE;
-        }
-        postResult(mLatestResult, codeResponseJson);
-    }
-
-    
-    private boolean isOnline() {
-        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
-        return cm != null && cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
-    }
-
-    private void postResult(final ResultOAuthType result,final JSONObject codeResponseJson) {
-        if (mHandler != null && mListener != null) {
-            mHandler.post(new Runnable() {
-                @Override
-                public void run() {
-                    mListener.onOAuth2GetCodeResult(result, codeResponseJson);
-                }
-            });
-        }
-    }
-
-}

+ 1 - 20
src/com/owncloud/android/network/OwnCloudClientUtils.java

@@ -130,26 +130,7 @@ public class OwnCloudClientUtils {
         
         return client;
     }
-    
-    /**
-     * Creates a WebdavClient to try a new account before saving it
-     * 
-     * @param uri       URL to the ownCloud server
-     * @param username  User name
-     * @param password  User password
-     * @param context   Android context where the WebdavClient is being created.
-     * @return          A WebdavClient object ready to be used
-     */
-    public static WebdavClient createOwnCloudClient(Uri uri, String username, String password, Context context) {
-        //Log.d(TAG, "Creating WebdavClient for " + username + "@" + uri);
-        
-        WebdavClient client = createOwnCloudClient(uri, context);
-        
-        client.setBasicCredentials(username, password);
-        
-        return client;
-    }
-    
+
     
     /**
      * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections.

+ 0 - 138
src/com/owncloud/android/operations/ConnectionCheckOperation.java

@@ -1,138 +0,0 @@
-/* ownCloud Android client application
- *   Copyright (C) 2012 Bartek Przybylski
- *
- *   This program is free software: you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation, either version 3 of the License, or
- *   (at your option) any later version.
- *
- *   This program is distributed in the hope that it will be useful,
- *   but WITHOUT ANY WARRANTY; without even the implied warranty of
- *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *   GNU General Public License for more details.
- *
- *   You should have received a copy of the GNU General Public License
- *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
- *
- */
-
-package com.owncloud.android.operations;
-
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import com.owncloud.android.AccountUtils;
-import com.owncloud.android.utils.OwnCloudVersion;
-
-import eu.alefzero.webdav.WebdavClient;
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.Uri;
-import android.util.Log;
-
-public class ConnectionCheckOperation extends RemoteOperation {
-    
-    /** Maximum time to wait for a response from the server when the connection is being tested, in MILLISECONDs.  */
-    public static final int TRY_CONNECTION_TIMEOUT = 5000;
-    
-    private static final String TAG = ConnectionCheckOperation.class.getSimpleName();
-    
-    private String mUrl;
-    private RemoteOperationResult mLatestResult;
-    private Context mContext;
-    private OwnCloudVersion mOCVersion;
-
-    public ConnectionCheckOperation(String url, Context context) {
-        mUrl = url;
-        mContext = context;
-        mOCVersion = null;
-    }
-    
-    public OwnCloudVersion getDiscoveredVersion() {
-        return mOCVersion;
-    }
-
-    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);
-            }
-
-        } 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.i(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage());
-            
-        } else if (mLatestResult.getException() != null) {
-            Log.e(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage(), mLatestResult.getException());
-            
-        } else {
-            Log.e(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage());
-        }
-
-        return retval;
-    }
-
-    private boolean isOnline() {
-        ConnectivityManager cm = (ConnectivityManager) mContext
-                .getSystemService(Context.CONNECTIVITY_SERVICE);
-        return cm != null && cm.getActiveNetworkInfo() != null
-                && cm.getActiveNetworkInfo().isConnectedOrConnecting();
-    }
-
-	@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.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;
-	}
-	
-}

+ 0 - 20
src/com/owncloud/android/operations/ExistenceCheckOperation.java

@@ -41,20 +41,6 @@ public class ExistenceCheckOperation extends RemoteOperation {
     private String mPath;
     private Context mContext;
     private boolean mSuccessIfAbsent;
-    private String mAccessToken;
-
-    
-    /**
-     * Simple constructor. Success when the path in the server exists.
-     * 
-     * @param path          Path to append to the URL owned by the client instance.
-     * @param context       Android application context.
-     * @param accessToken   Access token for Bearer Authentication -> TODO: move to other place
-     */
-    public ExistenceCheckOperation(String path, Context context, String accessToken) {
-        this(path, context, false);
-        mAccessToken = accessToken;
-    }
 
     
     /**
@@ -80,8 +66,6 @@ public class ExistenceCheckOperation extends RemoteOperation {
         HeadMethod head = null;
         try {
             head = new HeadMethod(client.getBaseUri() + mPath);
-            head.addRequestHeader("Authorization", "Bearer " + mAccessToken);   // TODO put in some general place
-            
             int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
             client.exhaustResponse(head.getResponseBodyAsStream());
             boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
@@ -107,8 +91,4 @@ public class ExistenceCheckOperation extends RemoteOperation {
     }
 
 
-    public String getAccessToken() {
-        return mAccessToken;
-    }
-
 }

+ 0 - 125
src/com/owncloud/android/operations/GetOAuth2AccessToken.java

@@ -1,125 +0,0 @@
-package com.owncloud.android.operations;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.NameValuePair;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import com.owncloud.android.authenticator.oauth2.OAuth2Context;
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
-
-import android.util.Log;
-
-import eu.alefzero.webdav.WebdavClient;
-
-public class GetOAuth2AccessToken extends RemoteOperation {
-    
-    private static final String TAG = GetOAuth2AccessToken.class.getSimpleName();
-    
-    private Map<String, String> mOAuth2AuthorizationResponse;
-    private Map<String, String> mResultTokenMap;
-
-    
-    public GetOAuth2AccessToken(Map<String, String> oAuth2AuthorizationResponse) {
-        mOAuth2AuthorizationResponse = oAuth2AuthorizationResponse;
-        mResultTokenMap = null;
-    }
-    
-    
-    public Map<String, String> getOauth2AutorizationResponse() {
-        return mOAuth2AuthorizationResponse;
-    }
-
-    public Map<String, String> getResultTokenMap() {
-        return mResultTokenMap;
-    }
-    
-    @Override
-    protected RemoteOperationResult run(WebdavClient client) {
-        RemoteOperationResult result = null;
-        PostMethod postMethod = null;
-        
-        try {
-            NameValuePair[] nameValuePairs = new NameValuePair[5];
-            nameValuePairs[0] = new NameValuePair(OAuth2Context.KEY_CLIENT_ID, OAuth2Context.OAUTH2_F_CLIENT_ID);
-            nameValuePairs[1] = new NameValuePair(OAuth2Context.KEY_CODE, mOAuth2AuthorizationResponse.get(OAuth2Context.KEY_CODE));            
-            nameValuePairs[2] = new NameValuePair(OAuth2Context.KEY_SCOPE, mOAuth2AuthorizationResponse.get(OAuth2Context.KEY_SCOPE));            
-            nameValuePairs[3] = new NameValuePair(OAuth2Context.KEY_REDIRECT_URI, OAuth2Context.MY_REDIRECT_URI);            
-            nameValuePairs[4] = new NameValuePair(OAuth2Context.KEY_GRANT_TYPE, OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE);
-            
-            postMethod = new PostMethod(client.getBaseUri().toString());
-            postMethod.setRequestBody(nameValuePairs);
-            int status = client.executeMethod(postMethod);
-            if (status >= 300) {
-                client.exhaustResponse(postMethod.getResponseBodyAsStream());
-                result = new RemoteOperationResult(false, status);
-                
-            } else {
-                JSONObject tokenJson = new JSONObject(postMethod.getResponseBodyAsString());
-                parseResult(tokenJson);
-                if (mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR) != null) {
-                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
-                    
-                } else {
-                    result = new RemoteOperationResult(true, status);
-                }
-            }
-
-        } catch (Exception e) {
-            result = new RemoteOperationResult(e);
-            
-        } finally {
-            if (postMethod != null)
-                postMethod.releaseConnection();    // let the connection available for other methods
-            
-            if (result.isSuccess()) {
-                Log.i(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
-            
-            } else if (result.getException() != null) {
-                Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage(), result.getException());
-                
-            } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
-                    Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + mResultTokenMap.get(OAuth2Context.OAUTH2_TOKEN_RECEIVED_ERROR));
-                    
-            } else {
-                Log.e(TAG, "OAuth2 TOKEN REQUEST with code " + mOAuth2AuthorizationResponse.get("code") + " to " + client.getBaseUri() + ": " + result.getLogMessage());
-            }
-        }
-        
-        return result;
-    }
-    
-    
-    private void parseResult (JSONObject tokenJson) throws JSONException {
-        mResultTokenMap = new HashMap<String, String>();
-        
-        if (tokenJson.has(OAuth2Context.KEY_ACCESS_TOKEN)) {
-            mResultTokenMap.put(OAuth2Context.KEY_ACCESS_TOKEN, tokenJson.getString(OAuth2Context.KEY_ACCESS_TOKEN));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_TOKEN_TYPE)) {
-            mResultTokenMap.put(OAuth2Context.KEY_TOKEN_TYPE, tokenJson.getString(OAuth2Context.KEY_TOKEN_TYPE));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_EXPIRES_IN)) {
-            mResultTokenMap.put(OAuth2Context.KEY_EXPIRES_IN, tokenJson.getString(OAuth2Context.KEY_EXPIRES_IN));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_REFRESH_TOKEN)) {
-            mResultTokenMap.put(OAuth2Context.KEY_REFRESH_TOKEN, tokenJson.getString(OAuth2Context.KEY_REFRESH_TOKEN));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_SCOPE)) {
-            mResultTokenMap.put(OAuth2Context.KEY_SCOPE, tokenJson.getString(OAuth2Context.KEY_SCOPE));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_ERROR)) {
-            mResultTokenMap.put(OAuth2Context.KEY_ERROR, tokenJson.getString(OAuth2Context.KEY_ERROR));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_ERROR_DESCRIPTION)) {
-            mResultTokenMap.put(OAuth2Context.KEY_ERROR_DESCRIPTION, tokenJson.getString(OAuth2Context.KEY_ERROR_DESCRIPTION));
-        }
-        if (tokenJson.has(OAuth2Context.KEY_ERROR_URI)) {
-            mResultTokenMap.put(OAuth2Context.KEY_ERROR_URI, tokenJson.getString(OAuth2Context.KEY_ERROR_URI));
-        }
-    }
-
-}

+ 3 - 3
src/com/owncloud/android/ui/activity/AccountSelectActivity.java

@@ -94,10 +94,10 @@ public class AccountSelectActivity extends SherlockListActivity implements
                 /// the account set as default changed since this activity was created 
             
                 // trigger synchronization
-                ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE);
+                ContentResolver.cancelSync(null, AccountAuthenticator.AUTHORITY);
                 Bundle bundle = new Bundle();
                 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
-                ContentResolver.requestSync(AccountUtils.getCurrentOwnCloudAccount(this), AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
+                ContentResolver.requestSync(AccountUtils.getCurrentOwnCloudAccount(this), AccountAuthenticator.AUTHORITY, bundle);
                 
                 // restart the main activity
                 Intent i = new Intent(this, FileDisplayActivity.class);
@@ -135,7 +135,7 @@ public class AccountSelectActivity extends SherlockListActivity implements
             Intent intent = new Intent(
                     android.provider.Settings.ACTION_ADD_ACCOUNT);
             intent.putExtra("authorities",
-                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+                    new String[] { AccountAuthenticator.AUTHORITY });
             startActivity(intent);
             return true;
         }

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 752 - 156
src/com/owncloud/android/ui/activity/AuthenticatorActivity.java


+ 3 - 3
src/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -217,7 +217,7 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
      */
     private void createFirstAccount() {
         Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
-        intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+        intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTHORITY });
         startActivity(intent);  // the new activity won't be created until this.onStart() and this.onResume() are finished;
     }
 
@@ -346,12 +346,12 @@ public class FileDisplayActivity extends SherlockFragmentActivity implements
     }
 
     private void startSynchronization() {
-        ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE);   // cancel the current synchronizations of any ownCloud account
+        ContentResolver.cancelSync(null, AccountAuthenticator.AUTHORITY);   // cancel the current synchronizations of any ownCloud account
         Bundle bundle = new Bundle();
         bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
         ContentResolver.requestSync(
                 AccountUtils.getCurrentOwnCloudAccount(this),
-                AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
+                AccountAuthenticator.AUTHORITY, bundle);
     }
 
 

+ 2 - 2
src/com/owncloud/android/ui/activity/LandingActivity.java

@@ -113,9 +113,9 @@ public class LandingActivity extends SherlockFragmentActivity implements
         dialog.dismiss();
         switch (which) {
         case DialogInterface.BUTTON_POSITIVE:
-            Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
+            Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
             intent.putExtra("authorities",
-                    new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+                    new String[] { AccountAuthenticator.AUTHORITY });
             startActivity(intent);
             break;
         case DialogInterface.BUTTON_NEGATIVE:

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно