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

codacy: Avoid reassigning parameters and extract util methods to proper util class

# Conflicts:
#	src/main/java/com/owncloud/android/ui/dialog/ShareLinkToDialog.java
AndyScherzinger 7 жил өмнө
parent
commit
098241eea8

+ 117 - 8
src/main/java/com/owncloud/android/authentication/AccountUtils.java

@@ -30,7 +30,6 @@ import android.support.annotation.Nullable;
 import com.owncloud.android.MainApp;
 import com.owncloud.android.datamodel.ArbitraryDataProvider;
 import com.owncloud.android.datamodel.FileDataStorageManager;
-import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.utils.Log_OC;
@@ -41,15 +40,8 @@ import com.owncloud.android.ui.activity.ManageAccountsActivity;
 import java.util.Locale;
 
 public class AccountUtils {
-
     private static final String TAG = AccountUtils.class.getSimpleName();
 
-    public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
-    public static final String DAV_PATH = "/remote.php/dav";
-    private static final String ODAV_PATH = "/remote.php/odav";
-    private static final String SAML_SSO_PATH = "/remote.php/webdav";
-    public static final String STATUS_PATH = "/status.php";
-
     public static final int ACCOUNT_VERSION = 1;
     public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
     public static final String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
@@ -243,6 +235,123 @@ public class AccountUtils {
         return url;
     }
 
+     * Update the accounts in AccountManager to meet the current version of accounts expected by the app, if needed.
+     *
+     * Introduced to handle a change in the structure of stored account names needed to allow different OC servers
+     * in the same domain, but not in the same path.
+     *
+     * @param   context     Used to access the AccountManager.
+     */
+    public static void updateAccountVersion(Context context) {
+        Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
+        AccountManager accountMgr = AccountManager.get(context);
+
+        if ( currentAccount != null ) {
+            String currentAccountVersion = accountMgr.getUserData(currentAccount, Constants.KEY_OC_ACCOUNT_VERSION);
+
+            if (!String.valueOf(ACCOUNT_VERSION_WITH_PROPER_ID).equalsIgnoreCase(currentAccountVersion)) {
+                Log_OC.i(TAG, "Upgrading accounts to account version #" + ACCOUNT_VERSION_WITH_PROPER_ID);
+                Account[] ocAccounts = accountMgr.getAccountsByType(MainApp.getAccountType());
+                String serverUrl;
+                String username;
+                String newAccountName;
+                String password;
+                Account newAccount;
+                for (Account account : ocAccounts) {
+                    // build new account name
+                    serverUrl = accountMgr.getUserData(account, Constants.KEY_OC_BASE_URL);
+
+                    // update user name
+                    try {
+                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
+                        OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton()
+                                .getClientFor(ocAccount, context);
+
+                        GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation();
+                        RemoteOperationResult result = remoteUserNameOperation.execute(client);
+
+                        if (result.isSuccess()) {
+                            UserInfo userInfo = (UserInfo) result.getData().get(0);
+                            username = userInfo.id;
+                        } else {
+                            // skip account, try it next time
+                            Log_OC.e(TAG, "Error while getting username for account: " + account.name);
+                            continue;
+                        }
+                    } catch (Exception e) {
+                        Log_OC.e(TAG, "Error while getting username: " + e.getMessage());
+                        continue;
+                    }
+
+                    newAccountName = com.owncloud.android.lib.common.accounts.AccountUtils.
+                            buildAccountName(Uri.parse(serverUrl), username);
+
+                    // migrate to a new account, if needed
+                    if (!newAccountName.equals(account.name)) {
+                        Log_OC.d(TAG, "Upgrading " + account.name + " to " + newAccountName);
+
+                        // create the new account
+                        newAccount = new Account(newAccountName, MainApp.getAccountType());
+                        password = accountMgr.getPassword(account);
+                        accountMgr.addAccountExplicitly(newAccount, (password != null) ? password : "", null);
+
+                        // copy base URL
+                        accountMgr.setUserData(newAccount, Constants.KEY_OC_BASE_URL, serverUrl);
+
+                        // copy server version
+                        accountMgr.setUserData(
+                                newAccount,
+                                Constants.KEY_OC_VERSION,
+                                accountMgr.getUserData(account, Constants.KEY_OC_VERSION)
+                        );
+
+                        // copy cookies
+                        accountMgr.setUserData(
+                                newAccount,
+                                Constants.KEY_COOKIES,
+                                accountMgr.getUserData(account, Constants.KEY_COOKIES)
+                        );
+
+                        // copy type of authentication
+                        final String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO);
+                        if (Boolean.parseBoolean(isSamlStr)) {
+                            accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
+                        }
+
+                        final String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2);
+                        if (Boolean.parseBoolean(isOauthStr)) {
+                            accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
+                        }
+                        /* TODO - study if it's possible to run this method in a background thread to copy the authToken
+                        if (isOAuth || isSaml) {
+                            accountMgr.setAuthToken(newAccount, mAuthTokenType, mAuthToken);
+                        }
+                        */
+
+                        // don't forget the account saved in preferences as the current one
+                        if (currentAccount.name.equals(account.name)) {
+                            AccountUtils.setCurrentOwnCloudAccount(context, newAccountName);
+                        }
+
+                        // remove the old account
+                        accountMgr.removeAccount(account, null, null);
+                            // will assume it succeeds, not a big deal otherwise
+
+                    } else {
+                        // servers which base URL is in the root of their domain need no change
+                        Log_OC.d(TAG, account.name + " needs no upgrade ");
+                        newAccount = account;
+                    }
+
+                    // at least, upgrade account version
+                    Log_OC.d(TAG, "Setting version " + ACCOUNT_VERSION_WITH_PROPER_ID + " to " + newAccountName);
+                    accountMgr.setUserData(newAccount,
+                            Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(ACCOUNT_VERSION_WITH_PROPER_ID));
+                }
+            }
+        }
+    }
+
     /**
      * Access the version of the OC server corresponding to an account SAVED IN THE ACCOUNTMANAGER
      *

+ 9 - 58
src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java

@@ -456,12 +456,11 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
 
         if (loginUrlInfo != null) {
-            mServerInfo.mBaseUrl = normalizeUrlSuffix(loginUrlInfo.serverAddress);
+            mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
             webViewUser = loginUrlInfo.username;
             webViewPassword = loginUrlInfo.password;
             checkOcServer();
         }
-
     }
 
     private void populateLoginFields(String dataString) throws IllegalArgumentException {
@@ -683,7 +682,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                 public void afterTextChanged(Editable s) {
                     if (mOkButton.isEnabled() &&
                             !mServerInfo.mBaseUrl.equals(
-                                    normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
+                                    AuthenticatorUrlUtils.normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
                         mOkButton.setEnabled(false);
                     }
                 }
@@ -1070,7 +1069,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      */
     private void onUrlInputFocusLost() {
         if (!mServerInfo.mBaseUrl.equals(
-                normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
+                AuthenticatorUrlUtils.normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
             // check server again only if the user changed something in the field
             checkOcServer();
         } else {
@@ -1096,7 +1095,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         if (uri.length() != 0) {
             if (mHostUrlInput != null) {
-                uri = stripIndexPhpOrAppsFiles(uri, mHostUrlInput);
+                uri = AuthenticatorUrlUtils.stripIndexPhpOrAppsFiles(uri);
+                mHostUrlInput.setText(uri);
             }
 
             // Handle internationalized domain names
@@ -1114,7 +1114,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
             Intent getServerInfoIntent = new Intent();
             getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
-            getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, normalizeUrlSuffix(uri));
+            getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,
+                    AuthenticatorUrlUtils.normalizeUrlSuffix(uri));
 
             if (mOperationsServiceBinder != null) {
                 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
@@ -1302,7 +1303,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         /// Show SAML-based SSO web dialog
         String targetUrl = mServerInfo.mBaseUrl
-                + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
+                + AuthenticatorUrlUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
         SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
         dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
     }
@@ -1476,56 +1477,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         );
     }
 
-
-    // TODO remove, if possible
-    private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
-
-        if (url != null && url.length() > 0) {
-            url = url.trim();
-            if (!url.toLowerCase().startsWith(HTTP_PROTOCOL) &&
-                    !url.toLowerCase().startsWith(HTTP_PROTOCOL)) {
-                if (sslWhenUnprefixed) {
-                    url = HTTPS_PROTOCOL + url;
-                } else {
-                    url = HTTP_PROTOCOL + url;
-                }
-            }
-
-            url = normalizeUrlSuffix(url);
-        }
-        return (url != null ? url : "");
-    }
-
-
-    private String normalizeUrlSuffix(String url) {
-        if (url.endsWith("/")) {
-            url = url.substring(0, url.length() - 1);
-        }
-        url = trimUrlWebdav(url);
-        return url;
-    }
-
-    private String stripIndexPhpOrAppsFiles(String url, EditText mHostUrlInput) {
-        if (url.endsWith("/index.php")) {
-            url = url.substring(0, url.lastIndexOf("/index.php"));
-            mHostUrlInput.setText(url);
-        } else if (url.contains("/index.php/apps/")) {
-            url = url.substring(0, url.lastIndexOf("/index.php/apps/"));
-            mHostUrlInput.setText(url);
-        }
-
-        return url;
-    }
-
-    // TODO remove, if possible
-    private String trimUrlWebdav(String url) {
-        if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)) {
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
-        }
-        return url;
-    }
-
-
     /**
      * Chooses the right icon and text to show to the user for the received operation result.
      *
@@ -1873,7 +1824,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         String lastPermanentLocation = authResult.getLastPermanentLocation();
         if (lastPermanentLocation != null) {
-            mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
+            mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
         }
 
         Uri uri = Uri.parse(mServerInfo.mBaseUrl);

+ 129 - 0
src/main/java/com/owncloud/android/authentication/AuthenticatorUrlUtils.java

@@ -0,0 +1,129 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Andy Scherzinger
+ * Copyright (C) 2017 Andy Scherzinger
+ * Copyright (C) 2012 Bartek Przybylski
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero 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 Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package com.owncloud.android.authentication;
+
+import com.owncloud.android.MainApp;
+import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
+import com.owncloud.android.lib.resources.status.OwnCloudVersion;
+
+/**
+ * Helper class for authenticator-URL related logic.
+ */
+public abstract class AuthenticatorUrlUtils {
+    public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
+
+    private static final String HTTPS_PROTOCOL = "https://";
+    private static final String HTTP_PROTOCOL = "http://";
+
+    private static final String ODAV_PATH = "/remote.php/odav";
+    private static final String SAML_SSO_PATH = "/remote.php/webdav";
+
+    /**
+     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,
+     * according to its version and the authorization method used.
+     *
+     * @param   version         Version of ownCloud server.
+     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in
+     *                          {@link AccountAuthenticator}.
+     * @return                  WebDAV path for given OC version and authorization method, null if OC version
+     *                          is unknown; versions prior to ownCloud 4 are not supported anymore
+     */
+    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {
+        if (version != null) {
+            if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(authTokenType)) {
+                return ODAV_PATH;
+            }
+            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(authTokenType)) {
+                return SAML_SSO_PATH;
+            }
+
+            return WEBDAV_PATH_4_0_AND_LATER;
+        }
+        return null;
+    }
+
+    public static String normalizeUrlSuffix(String url) {
+        if (url.endsWith("/")) {
+            url = url.substring(0, url.length() - 1);
+        }
+        return trimUrlWebdav(url);
+    }
+
+    public static String normalizeUrl(String url, boolean sslWhenUnprefixed) {
+        String normalizedUrl = url;
+
+        if (normalizedUrl != null && normalizedUrl.length() > 0) {
+            normalizedUrl = normalizedUrl.trim();
+
+            if (!normalizedUrl.toLowerCase().startsWith(HTTP_PROTOCOL) &&
+                    !normalizedUrl.toLowerCase().startsWith(HTTP_PROTOCOL)) {
+                if (sslWhenUnprefixed) {
+                    normalizedUrl = HTTPS_PROTOCOL + normalizedUrl;
+                } else {
+                    normalizedUrl = HTTP_PROTOCOL + normalizedUrl;
+                }
+            }
+
+            normalizedUrl = normalizeUrlSuffix(normalizedUrl);
+        }
+        return (normalizedUrl != null ? normalizedUrl : "");
+    }
+
+    public static String trimWebdavSuffix(String url) {
+        String trimmedUrl = url;
+        while(trimmedUrl.endsWith("/")) {
+            trimmedUrl = trimmedUrl.substring(0, url.length() - 1);
+        }
+
+        int pos = trimmedUrl.lastIndexOf(WEBDAV_PATH_4_0_AND_LATER);
+        if (pos >= 0) {
+            trimmedUrl = trimmedUrl.substring(0, pos);
+
+        } else {
+            pos = trimmedUrl.lastIndexOf(ODAV_PATH);
+            if (pos >= 0) {
+                trimmedUrl = trimmedUrl.substring(0, pos);
+            }
+        }
+
+        return trimmedUrl;
+    }
+
+    private static String trimUrlWebdav(String url) {
+        if (url.toLowerCase().endsWith(WEBDAV_PATH_4_0_AND_LATER)) {
+            return url.substring(0, url.length() - WEBDAV_PATH_4_0_AND_LATER.length());
+        }
+
+        return url;
+    }
+
+    public static String stripIndexPhpOrAppsFiles(String url) {
+        String strippedUrl = url;
+        if (strippedUrl.endsWith("/index.php")) {
+            strippedUrl = strippedUrl.substring(0, strippedUrl.lastIndexOf("/index.php"));
+        } else if (strippedUrl.contains("/index.php/apps/")) {
+            strippedUrl = strippedUrl.substring(0, strippedUrl.lastIndexOf("/index.php/apps/"));
+        }
+
+        return strippedUrl;
+    }
+}

+ 11 - 9
src/main/java/com/owncloud/android/operations/GetServerInfoOperation.java

@@ -23,7 +23,7 @@ package com.owncloud.android.operations;
 
 import android.content.Context;
 
-import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.authentication.AuthenticatorUrlUtils;
 import com.owncloud.android.lib.common.OwnCloudClient;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@@ -109,20 +109,22 @@ public class GetServerInfoOperation extends RemoteOperation {
                 new DetectAuthenticationMethodOperation(mContext);
         return operation.execute(client);
     }
-    
+
 
     private String trimWebdavSuffix(String url) {
-        if (url == null) {
-            url = "";
+	    String trimmedUrl = url;
+        if (trimmedUrl == null) {
+            trimmedUrl = "";
         } else {
-            if (url.endsWith("/")) {
-                url = url.substring(0, url.length() - 1);
+            if (trimmedUrl.endsWith("/")) {
+                trimmedUrl = trimmedUrl.substring(0, trimmedUrl.length() - 1);
             }
-            if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){
-                url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
+            if(trimmedUrl.toLowerCase().endsWith(AuthenticatorUrlUtils.WEBDAV_PATH_4_0_AND_LATER)){
+                trimmedUrl = trimmedUrl.substring(0,
+                        trimmedUrl.length() - AuthenticatorUrlUtils.WEBDAV_PATH_4_0_AND_LATER.length());
             }
         }
-        return url;
+        return trimmedUrl;
     }
 
     

+ 3 - 2
src/main/java/com/owncloud/android/operations/UpdateOCVersionOperation.java

@@ -24,7 +24,6 @@ import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.content.Context;
 
-import com.owncloud.android.authentication.AccountUtils;
 import com.owncloud.android.lib.common.OwnCloudClient;
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
 import com.owncloud.android.lib.common.operations.RemoteOperation;
@@ -46,6 +45,8 @@ public class UpdateOCVersionOperation extends RemoteOperation {
 
     private static final String TAG = UpdateOCVersionOperation.class.getSimpleName();
 
+    private static final String STATUS_PATH = "/status.php";
+
     private Account mAccount;
     private Context mContext;
     private OwnCloudVersion mOwnCloudVersion;
@@ -62,7 +63,7 @@ public class UpdateOCVersionOperation extends RemoteOperation {
     protected RemoteOperationResult run(OwnCloudClient client) {
         AccountManager accountMngr = AccountManager.get(mContext); 
         String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
-        statUrl += AccountUtils.STATUS_PATH;
+        statUrl += STATUS_PATH;
         RemoteOperationResult result = null;
         GetMethod getMethod = null;
 

+ 3 - 1
src/main/java/com/owncloud/android/ui/activity/Preferences.java

@@ -96,6 +96,8 @@ public class Preferences extends PreferenceActivity
 
     private static final int ACTION_REQUEST_CODE_DAVDROID_SETUP = 10;
 
+    private static final String DAV_PATH = "/remote.php/dav";
+
     public static final String SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI = "SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI";
 
     /**
@@ -655,7 +657,7 @@ public class Preferences extends PreferenceActivity
         if (getPackageManager().resolveActivity(davDroidLoginIntent, 0) != null) {
             // arguments
             if (mUri != null) {
-                davDroidLoginIntent.putExtra("url", mUri.toString() + AccountUtils.DAV_PATH);
+                davDroidLoginIntent.putExtra("url", mUri.toString() + DAV_PATH);
             }
             davDroidLoginIntent.putExtra("username", AccountUtils.getAccountUsername(account.name));
             //loginIntent.putExtra("password", "...");

+ 6 - 4
src/main/java/com/owncloud/android/ui/dialog/ShareLinkToDialog.java

@@ -154,11 +154,13 @@ public class ShareLinkToDialog  extends DialogFragment {
         
         @Override
         public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
-            if (convertView == null) {
-                convertView = newView(parent);
+            View view = convertView;
+
+            if (view == null) {
+                view = newView(parent);
             }
-            bindView(position, convertView);
-            return convertView;
+            bindView(position, view);
+            return view;
         }
         
         private View newView(ViewGroup parent) {